Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing a jquery document.ready() call

How do I clear out anonymous functions that are set to trigger via a jQuery document.ready() call?

For example:

<script type="text/javascript">
    //some code sets a doc ready callback
    $(document).ready(function ()
    {
        alert('ready');
    });
    
    //my attempt to prevent the callback from happening
    window.onload = null;
    $(document).unbind("ready");
    
</script>

The alert happens regardless of my attempts to circumvent it. Is there any way to do this?

like image 784
Shane N Avatar asked Oct 18 '11 22:10

Shane N


1 Answers

You'd probably get the most appropriate answer if you described what problem you're really trying to solve.

jQuery doesn't have a publicly documented way to undo or block document.ready() handlers. If you control the code, you can use a global variable and a conditional like this:

var skipReady = false;
$(document).ready(function ()
{
    if (!skipReady) {
        alert('ready');
    }
});

// skip the document.ready code, if it hasn't already fired
skipReady = true;

Or, if you want to hack into jQuery a bit (beyond the documented interfaces), you can do this:

$(document).ready(function() {
    alert("ready");
});

// stop the ready handler
$.isReady = true;

You can see this last one work here: http://jsfiddle.net/jfriend00/ZjH2k/. This works because jQuery uses the property: $.isReady to keep track of whether it has already fired the ready handlers or not. Setting it to true makes it think it has already fired them so it won't every do it again.

like image 160
jfriend00 Avatar answered Oct 19 '22 01:10

jfriend00