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?

1 Answer 1

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

});
Sign up to request clarification or add additional context in comments.

2 Comments

I see. I am humbled by the simplicity and obviousness of this solution.
if the second ajax request needs to happen only after script.js is loaded, throw it in the first callback function which has loaded = true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.