Detect if script is already loaded or not

It seems that helloworld.js loads several times depending on the number of times I #load . I say this because when I look at the Google Tools Chromes Developer Tools Network tab, it shows helloworld.js as many times as I #load .

 $(document).ready(function() { $("#load").click(function(){ $.getScript('helloworld.js', function() { hello(); }); }); }); 

The hello() function is as follows:

 function hello(){ alert("hello"); } 

Is it possible to determine if helloworld.js ?

So, if it is not downloaded, download it, and if it is downloaded, do not download it.

This is what the developer tools show if I press the #load button 4 times:

enter image description here

+7
source share
4 answers

Another option is to run .getScript() , but let it take the script from the browser cache, so you won’t reload it every time.

To do this, add this code:

 $.ajaxSetup({ cache: true }); 

This is taken on the page.

+5
source

Set the flag on successful file upload. If the flag is set, skip downloading the file again.

Try this code,

  var isLoaded = 0; //Set the flag OFF $(document).ready(function() { $("#load").click(function(){ if(isLoaded){ //If flag is ON then return false alert("File already loaded"); return false; } $.getScript('helloworld.js', function() { isLoaded = 1; //Turn ON the flag hello(); }); }); }); 
+10
source

So, why not just fire the event like this:

 $("#load").one("click", function() { $load = $(this); $.getScript('helloworld.js', function() { hello(); // bind hello to the click event of load for subsequent calls $load.on('click', hello); }); }); 

This will prevent subsequent loads and avoid using the global

+8
source

You can create a helper function:

 var getScript = (function() { var loadedFiles = {}; return function(filename, callback) { if(loadedFiles[filename]) { callback(); } else { $.getScript(filename, function() { loadedFiles[filename] = true; callback(); }); } }; })(); 
+3
source

All Articles