简体   繁体   中英

Change order of JQuery ready calls

I need to order some onReady calls, I was looking at these questions here and here and found nothing. However it was quite long time ago, and maybe now there is something to workaround this. so I need to do something like this:

$(function (){ console.log('second call'); })
$(function (){ console.log('first call'); })

To clarify why i need to do this:

The reason why I need that is these calls are spread through all the application, and what the most important: some of them are from third party and I cannot control them. But I do need to call my methods at first place, and i need to place scripts at the very and of the document. The code I working on is the legacy code and I cannot change it a lot, so answers like reconsider the way you are doing it would make no much sense for me. I just wandering if it possible or any workaround.

If you want to control the order of function execution, you should put them in same callback function.

$(function() {
  console.log('second call');
  console.log('first call');
});

The principle is, the ready() function adds things to an array (readyList), and then executes them in the order added. Manipulating the readyList array may solve you requirement, as per this article here

You could use an array to store the functions and have one onReady call that invokes them in the right order.

var calls = [];

calls[2] = function() {
    console.log("third call");
};

calls[1] = function() {
    console.log("second call");
};

calls[0] = function() {
    console.log("first call");
};

$(function() {
    for (var index = 0; index < calls.length; index += 1) {
        calls[index]();
    }
});

I got around it by having a .ready() very early on (right after jQuery loads) that executes functions from an array. Because it's very early in the source code it's .ready() is executed first. Further down the page I can add functions to the array, so they all execute before any other .ready()s.

I've wrapped it up in a .beforeReady() function and put it on GitHub as jQuery-Before-Ready for anyone that is interested.

https://github.com/aim12340/jQuery-Before-Ready

usage:

$.beforeReady(function() {
    alert("Ere I am JH")
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM