Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 500
ILikeTacos Avatar asked May 30 '13 15:05

ILikeTacos


2 Answers

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); } 
like image 199
Mahn Avatar answered Sep 29 '22 04:09

Mahn


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')); 
like image 42
Mathletics Avatar answered Sep 29 '22 04:09

Mathletics