[英]Inclusion of external js file and calling a function inside the external js file does not work with same script tag
為什么有必要先包含一個外部js文件,然后使用新的腳本標記調用任何函數?
我正在測試代碼:
的test.html
<html>
<head>
</head>
<body>
<script src=test.js>test();</script>
</body>
</html>
test.js
function test(){
alert(1);
}
它不會顯示警告彈出窗口。
但是當我在代碼中分別在body或head中包含test.js時:
的test.html
<html>
<head>
</head>
<body>
<script src=test.js></script>
<script>test();</script>
</body>
</html>
它確實顯示了一個彈出窗口。 它與HTML解析器有什么關系嗎? 我甚至沒有在瀏覽器控制台中顯示ReferenceError,因此測試有一個引用,但它沒有執行。
必須按順序加載全局命名空間中的代碼,以便必須首先定義執行的代碼。
例如,如果a.js有......
var a = function() {
alert('a');
}
......而且b.js有......
a()
...那么你不希望在a.js之前包含b.js,或者a()將不可用。
對於上面,
<script src=test.js></script>
<script>test();</script>
再次它是相同的方式:首先包含文件,然后運行其內容。
發生這種情況是因為當您指定src屬性時,您告訴瀏覽器不要在此標記內查找javascript,而是從外部查找
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.