oshirowanen
oshirowanen

Reputation: 15925

Detect if script has already loaded or not

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

Upvotes: 8

Views: 17563

Answers (4)

Shadow Wizard
Shadow Wizard

Reputation: 66388

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.

Upvotes: 6

Gabe
Gabe

Reputation: 50493

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

Upvotes: 8

pimvdb
pimvdb

Reputation: 154848

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

Upvotes: 3

Muthu Kumaran
Muthu Kumaran

Reputation: 17910

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();

            });
        });

    });

Upvotes: 10

Related Questions