Without using any external library how can I wait for a script to load before using it.
In my case I'm loading the scripts using:
(function (w,d,t,s,e,r) {
e = d.createElement(o);
r = d.getElementsByTagName(o)[0];
e.async = 1;
e.src = g;
r.parentNode.insertBefore(e, r)
})(window, document, 'script', '//mydomain.com/path/to/script.js');
And later:
// then later I want to use some code form the script:
var obj = new classFromTheInjectedScript();
Is there away to wait for the script to load and then start using it?
Note: I have a way that I can trigger an event within the script I want to load and then listen to it as you can see below, but is this a good idea?
(function(w,d){
document.addEventListener('scriptLoadedCustomEvent',onScriptReady);
function onScriptReady(){
// what I need to do goes here!
}
})(window,document);
You should be able to do something like this!
var script = document.createElement('script');
script.src = url; //source
var callback = function (){
// do stuff after loaded
}
script.onload = callback;
document.head.appendChild(script); //inject where you need it to be
You can use onload
and onerror
events for <script>
tag. Good example here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With