html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>TEST</title>
<script type="text/javascript" charset="utf-8">
alert('1');
alert(document.getElementById('test'));
</script>
<script type="text/javascript" src="./test.js" charset="utf-8">
</script>
</head>
<body>
<div id='test'><div>
<script type="text/javascript" charset="utf-8">
alert('3');
var element2 = document.getElementById('test2');
alert(element2);
alert(document.body);
var element = document.createElement('DIV');
element.innerText = '134444';
document.body.appendChild(element);
</script>
</body>
</html>
JavaScript:
(function (){
alert('2');
var test = document.getElementById('test');
alert(test);
var element = document.createElement('DIV');
element.id = 'test2';
//此時test是null
if(test!=null){
test.appendChild(element);
}
var body = document.body;
//此時body是null
if(body!=null){
body.appendChild(element);
}
})();
Result:
alert順序: 1 null 2 null 3 null [Object HTML Body Element]
最後的HTML Body內容:
<body>
<div id="test">
<div>
<script type="text/javascript" charset="utf-8">
alert('3');
var element2 = document.getElementById('test2');
alert(element2);
alert(document.body);
var element = document.createElement('DIV');
element.innerText = '134444';
document.body.appendChild(element);
</script>
</div>
</div>
<div>134444</div>
</body>
ps:
如果要讓head裡的javascript不要那麼早載入
可以加上defer的標籤
<script type="text/javascript" defer="defer">
一直到html檔載入完後才執行
留言列表