I'm trying to load JS scripts dynamically, but using jQuery is not an option.
I checked jQuery source to see how getScript was implemented so that I could use that approach to load scripts using native JS. However, getScript only calls jQuery.get()
and I haven't been able to find where the get method is implemented.
So my question is,
What's a reliable way to implement my own getScript method using native JavaScript?
Thanks!
Here's a jQuery getScript alternative with callback functionality:
function getScript(source, callback) { var script = document.createElement('script'); var prior = document.getElementsByTagName('script')[0]; script.async = 1; script.onload = script.onreadystatechange = function( _, isAbort ) { if(isAbort || !script.readyState || /loaded|complete/.test(script.readyState) ) { script.onload = script.onreadystatechange = null; script = undefined; if(!isAbort && callback) setTimeout(callback, 0); } }; script.src = source; prior.parentNode.insertBefore(script, prior); }
You can fetch scripts like this:
(function(document, tag) { var scriptTag = document.createElement(tag), // create a script tag firstScriptTag = document.getElementsByTagName(tag)[0]; // find the first script tag in the document scriptTag.src = 'your-script.js'; // set the source of the script to your script firstScriptTag.parentNode.insertBefore(scriptTag, firstScriptTag); // append the script to the DOM }(document, 'script'));
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