开发者

Call function once in jquery ready queue

We have code that spits out sev开发者_如何学Goeral script blocks which add identical functions to the queue that gets called when the document is ready. For example:

$(document).ready(function(){
    alert('hey');
});
$(document).ready(function(){
    alert('hey');
});
$(document).ready(function(){
    alert('hey');
});

This is not causing any problems but of course its unnecessary to call the same code several times.

Without changing the code that generates the repeated blocks, is there a way to make jquery only run the first code block and skip the rest?

Keep in mind that there is the possibility that the ready queue has other functions before and after the repeated code.


I would use an object literal to wrap duplicate code, and set a boolean when it has been called once so it will not be run again:

$(document).ready(function(){
    DuplicateHelper.SomeMethod1();
});
$(document).ready(function(){
    DuplicateHelper.SomeMethod1();
});
$(document).ready(function(){
    DuplicateHelper.SomeMethod1();
});

var DuplicateHelper = {
    HasMethod1Run: false,

    SomeMethod1: function() {
        if (!this.HasMethod1Run) {
            // do logic

            this.HasMethod1Run = true;
        }
    }
}

EDIT

You don't have to use the object literal for the code if you are generating the code dynamically, but you can use the same principle with the boolean:

var runCode = true;

$(document).ready(function(){
    if (runCode) {
        DuplicateHelper.SomeMethod1();
        runCode = false;
    }
});
$(document).ready(function(){
    if (runCode) {
        DuplicateHelper.SomeMethod1();
        runCode = false;
    }
});
$(document).ready(function(){
    if (runCode) {
        DuplicateHelper.SomeMethod1();
        runCode = false;
    }
});

However, I agree with netbrain that this situation is indicative of problems elsewhere in the architecture of your solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜