美文网首页
html-Script加载过程测试

html-Script加载过程测试

作者: 陶宁 | 来源:发表于2018-02-23 20:15 被阅读0次

js在html中有三种插入的方法
1、行内
2、bead
3、外链
因为html文件在浏览器中的加载顺序 可能导致一些js文件的值不能取到:
比如下面的例子 同一个javaScript 在不同的位置 可能导致取值结果的不同
页面在加载到head内javaScript时还没有加载到 document.getElementById('h1');的值 所有此时的h1null
外链的js文件因为是document.ready 是在整个文件加载完之后才取值,所以虽然写在head里面仍然可以取到document.getElementById('h1');的值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script src="text.js" ></script>
    <script type="text/javascript">
        var h1 = document.getElementById('h1');
        console.log(h1);
    </script>
</head>
<body>
    <h1 onclick="alert('hello')" id="h1">hello world</h1>
    <script type="text/javascript">
        var h1 = document.getElementById('h1');
        console.log(h1);
    </script>
</body>
</html>

text.js:

$(document).ready(function(){
    var h1 = document.getElementById('h1');
    console.log(h1);
})

相关文章

网友评论

      本文标题:html-Script加载过程测试

      本文链接:https://www.haomeiwen.com/subject/vvxfxftx.html