Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
40
rated 0 times [  42] [ 2]  / answers: 1 / hits: 50654  / 11 Years ago, thu, may 30, 2013, 12:00:00

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!


More From » jquery

 Answers
48

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

[#77910] Wednesday, May 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jenamackennac

Total Points: 304
Total Questions: 110
Total Answers: 107

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
jenamackennac questions
Fri, Feb 18, 22, 00:00, 2 Years ago
Wed, Apr 21, 21, 00:00, 3 Years ago
Thu, Apr 1, 21, 00:00, 3 Years ago
Tue, Feb 2, 21, 00:00, 3 Years ago
;