简体   繁体   中英

javascript access web-based script on button click

How would I go about accessing a web-based script. I don't know if I'm wording that correctly. I just want to be able to click a button and run the function. That's not the issue. The issue is how do I go about putting it in a function.

     <script type="text/javascript" src="http://wwww.blah.com/blah?blah=blah"></script>

how would i get that to run on button click? I've tried every which way to put it in a function and call the function. No luck though.

var buildScript = function (url, optionalCallback) {
    var script = document.createElement("script"),
        parent = document.getElementsByTagName("script")[0].parentElement;

    script.onload = optionalCallback;
    script.src = url;
    parent.appendChild(script);
};


var button = document.getElementById("my-button");
button.onclick = function () { buildScript("//url.to.site/file.js"); };

Or optionally:

button.onclick = function () {
    buildScript("//url.to.site/file.js", function () {
        function_from_loaded_script();
    });
};

If you need it to do other stuff, you might need to be more specific.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM