javascript access web-based script on button click
-
26-06-2021 - |
Frage
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.
Lösung
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.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow