Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
27
rated 0 times [  28] [ 1]  / answers: 1 / hits: 35638  / 10 Years ago, mon, october 13, 2014, 12:00:00

I've been trying to load a big js script only once. I'm not loading it on page load as it is not needed then and will slow the page load down.



So I've been trying to load it with jQuery's $.getScript and Modernizr.load ( since I'm already using Modernizr ).



I've tried iterating through all the <script></script> elements and checking their src attributes and seeing if this script is one of them, but that still loaded them each time I ran the test.



I also tried setting a global variable to true at the beginning of the script and checking if that was set and it still loaded every time I checked.
Here is what I was doing in that instance:



Modernizr.load({
test:if(window.flag === undefined),
yep:'conversation.js',
callback:function(){
antecedent();
}
});


and var flag = true; was set at the first line of conversation.js



Does anyone have any ideas how I can get this script to load once when this test is called to check if it is has been loaded and only load it once then?



** Edit/Update: ** document.getElementsByTagName('head')[0].appendChild(document.createElement('sc‌​ript')).src = 'conversation.js'; could work, but how do I check if the script is already loaded or not and then only call this if it isn't already included?


More From » jquery

 Answers
16

First, you'll need to check if the script is already on the page:



var list = document.getElementsByTagName('script');
var i = list.length, flag = false;
while (i--) {
if (list[i].src === 'filePathToJSScript') {
flag = true;
break;
}
}

// if we didn't already find it on the page, add it
if (!flag) {
var tag = document.createElement('script');
tag.src = 'filePathToJSScript';
document.getElementsByTagName('body')[0].appendChild(tag);
}


The code in the conditional can be used to dynamically add scripts to the page.



ES 6 Update



ES 6 simplifies this quite a bit:



let scripts = Array
.from(document.querySelectorAll('script'))
.map(scr => scr.src);

if (!scripts.includes('filePathToJSScript')) {
// same as above
}

[#69151] Thursday, October 9, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaylynkarinam

Total Points: 740
Total Questions: 103
Total Answers: 103

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
jaylynkarinam questions
Tue, Jul 23, 19, 00:00, 5 Years ago
Fri, Jul 5, 19, 00:00, 5 Years ago
Fri, Apr 12, 19, 00:00, 5 Years ago
Wed, Oct 31, 18, 00:00, 6 Years ago
;