测试代码段一:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" href="http://www.twitter.com/test.css"> <script> console.log(‘loading script content.‘) window.onload = function () { console.log(‘onload 1.‘) } document.addEventListener(‘DOMContentLoaded‘,function(){ console.log(‘dom is ready.‘); }); addOnload(function(){ console.log(‘addOnload 1.‘); }); addOnload(function(){ console.log(‘addOnload 2.‘); }); addOnload(function(){ console.log(‘addOnload 3.‘); }); function addOnload(func){ var last = window.onload; window.onload = function(){ if(last) last(); func(); } } </script> </head> <body> <img src="http://www.twitter.com/test.jpg"> </body> </html>
故意链接到墙外,测试结果如下:
1. 第6行会阻塞第7行, (放在script前的link标签会阻塞script,如果把link放在script之后,则不会阻塞)
2. body中的img标签会阻塞window.onload事件。
3. body中的img标签不会阻塞dom ready事件。
二。 测试代码段2.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="underscore.js"></script> <script> (function(global){ var funcs = []; document.addEventListener(‘DOMContentLoaded‘,function(){ console.log(‘dom is ready.‘); _(funcs).each(function(f){ f(); }) }); global.addOnReady = function(f){ funcs.push(f); } })(window); window.onload = function(){ console.log(‘window onload.‘); }; addOnReady(function(){console.log(‘ready 1.‘)}); addOnReady(function(){console.log(‘ready 2.‘)}); addOnReady(function(){console.log(‘ready 3.‘)}); </script> </head> <body> <img src="http://www.twitter.com/test.jpg"> <script type="text/javascript"> addOnReady(function(){console.log(‘ready 4.‘)}); </script> </body> </html>
1. body中的img标签不会阻塞img标签后面的script
2. dom ready事件无视img标签,在页面打开瞬间控制台会打印出ready 1, ready 2 ready 3 ready 4!
代码段二的输出结果如下:
dom is ready.
onload.html:28 ready 1.
onload.html:29 ready 2.
onload.html:30 ready 3.
onload.html:39 ready 4.
onload.html:37 GET https://www.twitter.com/test.jpg net::ERR_CONNECTION_TIMED_OUT
onload.html:25 window onload.
时间: 2024-10-26 11:37:41