kdniazi
kdniazi

Reputation: 1

Limit usage of $(document).ready(function() { })

How can I check that my document only has one instance of $(document).ready(function()?

If it's included more than one time, can I somehow remove duplicate instances (similar to PHP's require_once(); function)?

Upvotes: 0

Views: 340

Answers (2)

Zevan
Zevan

Reputation: 10235

One option is to use bind and unbind:

  $(document).bind("ready",function(){
    console.log("zero");
  });

  $(document).bind("ready",function(){
    console.log("one");
  });

  // get rid of previous ready events
  $(document).unbind("ready");

  $(document).bind("ready",function(){
    console.log("two");
  });

In the above, the first and second ready events will never fire because unbind has been called. So you will get "two" in the console.

Upvotes: 0

user113716
user113716

Reputation: 322502

Are you saying that the exact same code could be added more than once?

If so, I suppose you could set a global property indicating if the code inside has already run, then test for that property inside the ready() handler.

$(document).ready(function() {

       // check a flag to see if this has been called yet
    if( !window.thisCodeHasRun ) {
           // set the flag to show this has been called
        window.thisCodeHasRun = true;

        /* run your code */
    }
});

It would be better to take care of this on the server side, but if you must do it client side, this should work.

Upvotes: 3

Related Questions