jQuery.getScript alternative in native JavaScript
45,836
Solution 1
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'));
Solution 2
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);
Author by
ILikeTacos
Experienced Software Engineer with extensive background in Web Applications Development using LAMP and MEAN stacks.
Updated on July 18, 2022Comments
-
ILikeTacos almost 2 years
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!
-
Mathletics almost 11 years@Baszz huh? It creates a script element, sets the source, and then appends it to the DOM with
insertBefore()
. Where do you see$.get
? -
Bas Slagter almost 11 yearsYou guys are right...thought it was about how the getScript() was implemented.
-
Mathletics almost 11 yearsI didn't vote, but I'd venture to guess that declaring a variable without
var
, unnecessarily setting thetype
and appending to thehead
irked someone enough to lose some rep over it. -
Mahn over 9 yearsHow would you go about adding a callback that fires when the script is done loading and parsing with this method?
-
Mathletics over 9 years@Mahn as this question is already answered you will have to ask a new one, but I'm happy to answer it if/when you do.
-
Mahn over 9 yearsNevermind, figured out. See here for those looking for the same: stackoverflow.com/a/28002292/1329367