window.onloadおよびdom readyテスト
2620 ワード
テストコードセグメント1:
わざと壁の外にリンクして、テストの結果は以下の通りです:1.6行目は7行目をブロックします(scriptの前にあるlinkラベルはscriptをブロックし、linkをscriptの後に置くとブロックしません)
2.bodyのimgタグがwindowをブロックします.onloadイベント.
3.bodyのimgタグはdom readyイベントをブロックしません.
二.コードセグメント2をテストする.
1.bodyの中のimgタグはimgタグの後ろのscript 2をブロックしない.dom readyイベントはimgタグを無視し、ページが開くとコンソールからready 1,ready 2 ready 3 ready 4が印刷されます!コードセグメント2の出力結果は以下の通りである: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.
<!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が印刷されます!コードセグメント2の出力結果は以下の通りである: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.