JQuery + head.js: How to run $ (document) .ready () manually from within a finished head.js callback?

I need to optimize the loading time of a web application that contains many javascript files included in each of the HTML pages. I want to try head.js on one of these pages to see if it improves loading time. In those JS files that are called when the DOM is loaded, there are many $(document).ready(callback) , while head.js still loads the remaining JS files.

Is there a way I could tell jQuery not to fire the ready event myself, but let me call it from within the finished head.js callback?

+4
source share
3 answers

I am not sure why you want to fire an event for a document manually.

Instead, sign and post your own events using the built-in trigger and bind jQuery functions. This is best practice and best practice.

Working JSFiddle Demo

+1
source

I did a little experiment. Sort of:

 <html> <head> <script src="head.js"></script> <script src="jquery.min.js"></script> </head> <body> <script type="text/javascript"> jQuery("document").ready(function() { console.log("ready.document"); }); </script> ... <script type="text/javascript"> head.js("a.js", "b.js", "c.js", "test.js", function() { console.log("init.scripts"); var millis = 2000; var date = new Date(); var curDate = null; do {curDate = new Date(); } while(curDate-date < millis); jQuery("#ddd").text(testTT); console.log("init.end"); }); </script> ... a lot of html content ... <div id="ddd"></div> ... <script type="text/javascript" > console.log("last line"); </script> </body> 

Test.js writes to the console and defines testTT . The result is as follows.

 last line init.testTT init.scripts init.end ready.document 

Thus, in this simple case (using jQuery 1.8), the code in the loaded * .js is first executed, then head.js is generated for the init event, as a result, the jQuery ready event is generated. Therefore, it should be nice to wait until jQuery generates a finished event. However, if this is still a problem, you can do the following.

 head.js("a.js", "b.js", "c.js", function() { jQuery("document").ready(function() { jQuery("body").trigger("your_event"); }); }); 

and instead of listening to jQuery("document").ready... in your * .js, start listening to the custom event that you fire jQuery("body").on("your_event", handler) .

0
source

create a function register it in the finished document

$(document).ready(readyFunc);

 readyFunction(){ /// something to do; } 

if you want to use them manually, you just need to call the readyFunction () function;

0
source

All Articles