I use jquery and requirejs with my projects. I recently found something that I never expected. What is it if I load jquery via requirejs. The DOM ready event always fires after the window.onload event.
Here is my example: http://jsbin.com/ozusIBE/2
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>JS Bin</title> </head> <body> <img src="http://thejetlife.com/wp-content/uploads/2013/06/Times_Square_New_York_City_HDR.jpg" /> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.5/require.min.js"></script> <script> window.onload = function () { console.log('window.onload'); }; $(function () { console.log('document.ready1'); }); requirejs.config({ paths: { jquery: ['//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min'] } }); require(['jquery'], function () { console.log('required moudels have been loaded'); $(function () { console.log('document.ready2'); }); }); </script> </body> </html>
When I load a page without a cache. Result in the console:
document.ready1 required moudels have been loaded window.onload document.ready2
Note that ready2 always starts after window.onload. If I changed the code a little, then it matters.
//do not use requirejs to load jquery //require(['jquery'], function () { require([], function () { console.log('required moudels have been loaded'); $(function () { console.log('document.ready2'); }); });
Result:
document.ready1 required moudels have been loaded document.ready2 window.onload
It seems that if I use requrejs to load jquery as an AMD module asynchronously. The DOM ready event is useless. Since the DOM ready event will fire after window.onload.
I do not know why this happened, and is there a way to solve this problem?
UPDATE:
Thanks dherman. As dherman said about document.readyState . I did a little investigation and found a solution to the problem. I tested it in Chrome and Firefox. It works well. However, this may not be the ideal solution, as all versions of IE can have an interactive state until the DOM is fully loaded. ( ref )
Here is my updated example: http://jsbin.com/ozusIBE/16
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>JS Bin</title> </head> <body> <img src="http://upload.wikimedia.org/wikipedia/commons/a/ab/NYC_-_Time_Square_-_From_upperstairs.jpg" /> <script src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.9/require.min.js"></script> <script> requirejs.config({ paths: { jquery: ['//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min'] } }); require(['jquery'], function () { console.log('required moudels have been loaded'); var init = function(){ console.log('document.ready'); }; if ( document.attachEvent ? document.readyState === 'complete' : document.readyState !== 'loading' ){ init(); }else{ $(function(){ init(); }); } }); window.onload = function () { console.log('window.onload'); }; </script> </body> </html>