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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top