Detect if script has already loaded or not
Asked Answered
H

4

8

It seems that helloworld.js gets loaded multiple times based on the number of times I click #load. I say this because when I look at Google Chromes Developer Tools Network tab, it shows helloworld.js as many times as I click #load.

$(document).ready(function() {

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

});

The hello() function looks like this:

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

Is it possible to detect if helloworld.js has already loaded?

So if it hasn't loaded, load it, and if it has loaded, don't load it.

This is what Developer Tools currently shows me if I click the #load button 4 times:

enter image description here

Hospitalize answered 14/11, 2012 at 15:28 Comment(5)
You can also let it use cache: $.ajaxSetup({ cache: true }); (taken from here).Blueprint
The calls should be cached already by the browser…Murder
@ShadowWizard, this seems to work, thanks. It should be an answer.Hospitalize
@Murder by default jQuery will add unique timestamp to each AJAX call so that it won't get cached. By setting the property to false it won't add any unique value.Blueprint
@Murder $.getScript is the exception, it defaults to cache:false unless specifically set in ajaxSetup. (per the documentation)Swann
B
6

Another option is letting .getScript() run but let it take the script from browser's cache so you won't have it reloaded each and every time.

To achieve this, add such code:

$.ajaxSetup({
    cache: true
});

This is taken from the documentation page.

Blueprint answered 14/11, 2012 at 15:55 Comment(4)
If the script file has some event binding code wouldn't the event bind multiple times, each time the file is loaded or taken from the cache?Oboe
@Reddy that is true, didn't think of it. My answer is an alternative to this other answer, which advice to use the .one() which I must admit is better in this case.Blueprint
no problem in your answer at all. Was just curious to know, Because I have a issue where I load a html page which has local scripts within it and the events are binding multiple times. Just wanted to know if it is the same when read from cache.Oboe
@Reddy yeah, it will probably bind them again indeed, though it's worth checking in depth.Blueprint
S
10

Set a flag when file loaded successfully. If flag is set then skip the file loading 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();

            });
        });

    });
Separatrix answered 14/11, 2012 at 15:41 Comment(0)
P
8

So why not only fire the event once 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); 
   });
});

That would prevent subsequent loads and avoids the use of a global

Population answered 14/11, 2012 at 15:43 Comment(2)
And to add, use $("#load").click(hello) after hello() to make subsequent clicks to #load call the hello method without re-loading the js.Swann
@Gabe, I need to run the hello() function many times, but need to load the helloworld.js only once.Hospitalize
B
6

Another option is letting .getScript() run but let it take the script from browser's cache so you won't have it reloaded each and every time.

To achieve this, add such code:

$.ajaxSetup({
    cache: true
});

This is taken from the documentation page.

Blueprint answered 14/11, 2012 at 15:55 Comment(4)
If the script file has some event binding code wouldn't the event bind multiple times, each time the file is loaded or taken from the cache?Oboe
@Reddy that is true, didn't think of it. My answer is an alternative to this other answer, which advice to use the .one() which I must admit is better in this case.Blueprint
no problem in your answer at all. Was just curious to know, Because I have a issue where I load a html page which has local scripts within it and the events are binding multiple times. Just wanted to know if it is the same when read from cache.Oboe
@Reddy yeah, it will probably bind them again indeed, though it's worth checking in depth.Blueprint
S
3

You could 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();
      });
    }
  };
})();
Skirr answered 14/11, 2012 at 15:43 Comment(3)
Implementing such a cache system is not that trivial. For instance, what if getScript is invoked multiple times for the same file name before the file in question is retrieved and executed?Secondhand
@Šime Vidas: Good point. On the other hand, that would only happen if you click multiple times very fast after each other, which may not be worth caring about.Skirr
As both my parents regularly double-click on buttons, and links on web-pages, I think this scenario would occur more often than you think :PSecondhand

© 2022 - 2024 — McMap. All rights reserved.