简体   繁体   English

来自其他脚本的变量有时无法加载

[英]Variable From Other Script Sometimes not Loading

I have Two JavaScript scripts linked to my HTML File in this order:我有两个 JavaScript 脚本按以下顺序链接到我的 HTML 文件:

<script src="first.js"></script>
<script src="second.js"></script>

first.js has a variable which is accessed by second.js. first.js 有一个由 second.js 访问的变量。 The Variable is Used by second.js at the end of the file and the variable is defined in first.js at the beginning.该变量在文件末尾由 second.js 使用,而该变量在开头的 first.js 中定义。 Whenever I reload the site, a console error occasionally comes up saying that the Variable in first.js is not defined.每当我重新加载站点时,偶尔会出现控制台错误,提示未定义 first.js 中的变量。

Uncaught ReferenceError: dbis not defined at second.js:80 Uncaught ReferenceError: dbis not defined at second.js:80

Why is this?为什么是这样? Thanks in Advance.提前致谢。

Full Example:完整示例:

first.js:首先.js:

var db = [{name: "Obj1", property: "property1"}, {name: "Obj2", property: "property2"}]; // At Line 8

second.js:第二个.js:

function loadDbItems() {
    for(i = 0; i < db.length; i++) {
        console.log(db[i].name); // Line is Near End of Script
    }
}

You can register the variable with window to make it global guaranteed.您可以使用window注册变量以使其全局保证。
See script example below.请参阅下面的脚本示例。

You should not pollute the window object with every little variable you need, but this way the variable will exist across scripts, provided the first one executes first.你不应该用你需要的每个小变量来污染window object,但是这样变量将存在于脚本中,前提是第一个先执行。

 window.db = [{name: "Obj1", property: "property1"}, {name: "Obj2", property: "property2"}];
 <html> <body onload="loadDbItems()"> <script> function loadDbItems() { for(var i = 0; i < window.db.length; i++) { console.log(window.db[i].name); } } </script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM