jQuery.getScript alternative in native JavaScript

ILikeTacos picture ILikeTacos · May 30, 2013 · Viewed 43.1k times · Source

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!

Answer

Mahn picture Mahn · Jan 17, 2015

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);
}