Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a JS file has been included already?

Tags:

I have split my javascript in different files. I want to prevent, that javascript files are loaded twice. How can I do that?

like image 926
confile Avatar asked Aug 09 '13 20:08

confile


People also ask

How do you check if JS file is cached?

To determine if the Javascript (or any element) was cached, what you want to look for is the "Size" column. Data that is browser-cached will show "(from cache)" as the Size value. If you see anything else for Size, that means it was loaded over the network and wasn't loaded from the browser cache.

How do I ensure JavaScript is loaded?

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 };


1 Answers

Here's a test to see if a script has been included based on the path to the js file:

function isScriptAlreadyIncluded(src){     var scripts = document.getElementsByTagName("script");     for(var i = 0; i < scripts.length; i++)         if(scripts[i].getAttribute('src') == src) return true;     return false; } 

It will work for all scripts not loaded through AJAX, though you may want to modify it if you have jsonp code running.

like image 154
cwallenpoole Avatar answered Sep 20 '22 03:09

cwallenpoole