简体   繁体   中英

jQuery + head.js: How to trigger $(document).ready() manually from inside ready callback of head.js?

I need to optimize the load time of a web application which contains lots of javascript files included in each of it's HTML pages. I want to try head.js in one such page to see if it improves load time. There are lots of $(document).ready(callback) callbacks in those JS files which are invoked when DOM is loaded while head.js is still downloading remaining JS files.

Is there a way I could tell jQuery not to trigger ready event on its own, rather let me trigger it from inside the ready callback of head.js?

I am unsure as to why you'd want to trigger the document ready event manually.

Instead, subscribe and publish your own events using jQuery's built-in trigger & bind functionality. This is best practice and the optimal solution.

Working JSFiddle Demo

I have made a small experiment. Something like:

<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>

The test.js writes to console and defines testTT . The result is following

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

Thus, in this simple case (using jQuery 1.8), first the code in loaded *.js is executed then head.js on init event is generated, finally jQuery ready event is generated. So it should be fine to wait until JQuery generates ready event. However if this is still an issue you could 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 listen to the custom event you are triggering jQuery("body").on("your_event", handler) .

create a function register it in document ready

$(document).ready(readyFunc);

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

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

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