Search code examples
javascriptjquerygetscript

jQuery.getScript alternative in native JavaScript


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!


Solution

  • 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'));