I have Two JavaScript scripts linked to my HTML File in this order:
<script src="first.js"></script>
<script src="second.js"></script>
first.js has a variable which is accessed by 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. Whenever I reload the site, a console error occasionally comes up saying that the Variable in first.js is not defined.
Uncaught ReferenceError: dbis not defined at second.js:80
Why is this? Thanks in Advance.
Full Example:
first.js:
var db = [{name: "Obj1", property: "property1"}, {name: "Obj2", property: "property2"}]; // At Line 8
second.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.
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.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>