![](/img/trans.png)
[英]Running multiple Javascript scripts only when certain HTML elements exist?
[英]Running order of multiple scripts in an HTML document?
我有一個發送到瀏覽器的 HTML 頁面,它包含幾個腳本標記。
這是我的index.html
文件:
<body>
<div id="app"></div>
<script src="src/index.js"></script>
<script>
window.test = true;
</script>
</body>
</html>
這是我的src/index.js
文件:
<script>
const test = () => {
if (window.test) {
console.log("wow!");
}
};
test();
</script>
在 HTML 文件中,我在運行src/index.js
后定義了window.test
。 src/index.js
僅在window.test
設置為true
時才會打印到控制台,但僅在之后設置為第二個腳本。
這些腳本的運行順序是什么? 是否可以保證window.test
將始終設置為true
,以便src/index.js
中的if
語句打印wow!
?
代碼沙盒: https://codesandbox.io/s/javascript-forked-utgh8?file=/index.html
在從 HTML 文件調用的 JS 中,腳本的順序就像它們在該文件中的寫入順序一樣,“始終”將按該順序排列,這意味着在您的示例window.test
中, index.js
中的值始終為 null 所以控制台中不會打印任何內容
保證測試 function 僅在設置變量后調用為什么不使用自定義事件
<script src="src/index.js"></script>
<script>
window.test = true;
const event = new Event('test-setted');
document.dispatchEvent(event);
</script>
在 index.js 中
<script>
const test = () => {
if (window.test) {
console.log("wow!");
}
};
document.addEventListener('test-setted', function (e) {
test();
}, false);
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.