jQuery.getScript alternative in native JavaScript jQuery.getScript alternative in native JavaScript javascript javascript

jQuery.getScript alternative in native JavaScript


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


use this

var js_script = document.createElement('script');js_script.type = "text/javascript";js_script.src = "http://www.example.com/script.js";js_script.async = true;document.getElementsByTagName('head')[0].appendChild(js_script);