Including External Javascript
So far we have looked a two different ways to include javaScript into our HTML pages:
In the head - executed when called
<html>
<head>
<script type="text/javascript">
JavaScript code
… …
</script>
</head>
<body>
… …
</body>
</html>
In the body - executed when the page loads
<html>
<head>
… …
</head>
<body>
<script type="text/javascript">
JavaScript code
… …
</script>
</body>
</html>
Including javaScript in a external file
Just like with CSS it's considered good practice to separate the javaScript code from our HTML. The <script> tag allows us to utilise the src attribute to include javaScript contained in an external file. The following conventions must be adhered to:
- The external file should have a
.jsextension - You do not need to use the
<script>tag in the external.jsfile
Below we include demo_script_src.js which lives int he
scriptsfolder
<html>
<head>
<script type="text/javascript" src="scripts/demo_script_src.js"></script>
</head>
<body>
....
</body>