newguy newguy - 5 months ago 17
Node.js Question

My frontend javascript file cannot access variables in other javascript file

The problem is that I try to put my codes in separate javascript files. And one file will refer to an variable in a file which is referenced in

index.html
file previously.

For instance, the two files in my public folder are
client.js
and
test.js
.

In my
client.js
file, I have these codes:

function init() {
var socket = io.connect();
var temp = x;
}

document.addEventListener("DOMContentLoaded", init, false);


In my
test.js
file, I have these codes:

var x = 5;


In my
index.html
file, I have these codes:

<!DOCTYPE html>
<html>
<head>
<title>Amazing Particle System</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<canvas id="particle"></canvas>
<script src="/socket.io/socket.io.js"></script>
<script scr="/test.js"></script>
<script src="/client.js"></script>
</body>
</html>


But when I run my code I always get the error:


client.js:15 Uncaught ReferenceError: x is not defined


In developer tool I cannot see my
test.js
file in sources tab.

Is there anything I have done wrong in my code? How can I fix the issue?

Answer

You have to correct a typo in <script scr="/test.js"></script>, you have wrote scr instead of src attribute.. That's why your script do not work as expected

Comments