1

I have a function which loads up relevant js functions on click using ajax's shorthand $.getScript()

It looks like this:

$('#button').click(function() {

    $.getScript('/script.js');

    $.ajax({
        type: 'GET',
        url: '/file.php',
        cache: false,
        success: function(data) {
            $('#window').html(data);
        }
     });

});

This works okay... until I click #button again and getScript loads script.js again meaning that any functions inside script.js get triggered not once, but twice.

In another thread somebody mentioned this is a cacheing issue and that since $.getScript() is merely shorthand for $.ajax() and that by default ajax requests do not cache scripts that one should do the long version with 'cache: true'.

So I tried:

$('#button').click(function() {

    $.ajax({
      url: 'script.js',
      dataType: 'script',
      cache: true,
      success: function(data) {

        $.ajax({
            type: 'GET',
            url: '/file.php',
            cache: false,
            success: function(data) {
                $('#window').html(data);
            }
         });

      }
    });
});

Unfortunately, I am still in the same boat and every time I click #button all my functions in script.js are being appended again and again.

What is one to do? How do you go about loading a script just once, and/or checking to see if the resource is already loaded and if so, don't bother loading it all again?

Community
  • 1
  • 1
willdanceforfun
  • 11,044
  • 31
  • 82
  • 122

1 Answers1

4

// in the scope of a doc ready so loaded isnt global:

var loaded = false;

$('#button').click(function() {

    if ( !loaded ) {
        $.getScript('/script.js', function() {
             loaded = true;
        });
    }

    $.ajax({
        type: 'GET',
        url: '/file.php',
        cache: false,
        success: function(data) {
            $('#window').html(data);
        }
     });

});
meder omuraliev
  • 183,342
  • 71
  • 393
  • 434