Why a simple <script src="..."> </script> doesn't work?

Viewed 26971

I'm working on a project, and I didn't understand why a call to external script doesn't work.

Then I just did a extremely simple page html which includes a script alert, as you can see below... Can you tell me what's the problem ? I believe the problem is not the code, but what else can it be?

My browser is a recent Chrome, and my OS is Ubuntu. My HTML file is index.html :

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>MyPage</title>
</head>
<body>
    <p>Blablabla</p>
    <script type="text/javascript" src="/script.js"></script>
</body>
</html>

The Javascript file is script.js in the same folder:

<script type="text/javascript">
alert('Hey');
</script>
5 Answers

Paths starting with / are absolute paths. If the script and the HTML page are in the same directory, the script's path is simply "script.js":

<script type="text/javascript" src="script.js"></script>
<!-- Here --------------------------^ -->

If the file is in the same folder remove the "/" from script.js

<script type="text/javascript" src="script.js"></script>

Also if the js file has the script tags remove them.

If you want the alert when the doc is ready, consider doing something like:

document.addEventListener("DOMContentLoaded", function(event) { 
  alert('Hey')
});

I think that the script in the file dosen't need this script tag

<script type="text/javascript">
alert('Hey');
</script>

you can make like this

alert('hey');

just that try out and check if the file path in html to the js file is the right one.

Hi you don't need the script tags in the file:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>MyPage</title>
</head>
<body>
    <p>Blablabla</p>
    <script type="text/javascript" src="/script.js"></script>
</body>
</html>

The Javascript file is script.js in the same folder:

alert('Hey');

I have solve this problem by using Visual Studio. Just open the html file in VS and then run this file from here. It will connect your js file to html.

Related