大佬教程收集整理的这篇文章主要介绍了jquery – 为什么DOM ready事件总是在带有requirejs的window.onload事件之后运行?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我的例子: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>
当我加载没有缓存的页面.控制台的结果是:
document.ready1 required moudels have been loaded window.onload document.ready2
请注意,ready2始终在window.onload之后运行.
如果我稍微更改一下代码,那就会有所不同.
//do not use requirejs to load jquery //require(['jquery'],function () { require([],function () { console.log('required moudels have been loaded'); $(function () { console.log('document.ready2'); }); });
结果是:
document.ready1 required moudels have been loaded document.ready2 window.onload
似乎如果我使用requrejs异步加载jquery作为AMD模块. DOM ready事件没用.因为DOM就绪事件将在window.onload之后触发.
我不知道为什么会这样,有什么办法可以解决这个问题吗?
更新:
感谢dheRMAN.
正如dheRMAN提到的document.readyState.我做了一些小调查,找到了解决这个问题的方法.我在Chrome和Firefox上测试过它.它运作良好.但是,它可能不是一个完美的解决方案,因为所有版本的IE都可以在DOM完全加载之前具有交互状态. (ref)
这是我更新的例子: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>
以上是大佬教程为你收集整理的jquery – 为什么DOM ready事件总是在带有requirejs的window.onload事件之后运行?全部内容,希望文章能够帮你解决jquery – 为什么DOM ready事件总是在带有requirejs的window.onload事件之后运行?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。