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('script')).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?
What is the best way to make sure javascript is running when page is fully loaded? If you mean "fully loaded" literally, i.e., all images and other resources downloaded, then you have to use an onload handler, e.g.: window. onload = function() { // Everything has loaded, so put your code here };
Dynamic loading In some situations, we want to load third-party script files dynamically in JavaScript. Those files can be loaded asynchronously in JavaScript. To load a JavaScript file dynamically: Create a script element. Set the src , async , and type attributes.
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 simplifies this quite a bit:
let scripts = Array
.from(document.querySelectorAll('script'))
.map(scr => scr.src);
if (!scripts.includes('filePathToJSScript')) {
// same as above
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With