Learn how to link to an external JavaScript document to your web pages.
You have an HTML page. You want to add some JavaScript code to it (think slideshow, carousel, something you’ve written yourself). To get the two to work together you need to know how to link JavaScript to HTML. The good news is, it’s as simple as adding another tag to your HTML. But… It’s important to put the tag in the right place.
The tag to use to link JavaScript to HTML
The tag you need to use to link JavaScript to HTML is the tag.
<script src="myScriptFile.js"></script>
That's it! The tag just has the src attribute where you put the path to the JavaScript file you want to link. You can specify any relative path or a complete URL. For example, if your JavaScript file is stored in a sub-folder of your main project folder you would include that in the path.
<script src="js/myScriptFile.js"></script>
Or you can load a script straight from a URL. Like when you are loading something from a CDN.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Note, the closing tag.
Where to put the tag
OK, so now you know which tag to use to link JavaScript to HTML but where do you put it in your document? The answer is, as long as you get it somewhere on the page (and the path is right!), it will work. The choice of where you put it can affect the load times of your pages and slowing down your site.
Choice 1: In thetag
This is the place where a lot of tutorials will advise you to link JavaScript to HTML and it works fine. The problem is, this blocks the loading of your page. This isn’t a problem if your JavaScript is a couple of kilobytes. But it can stop your entire page loading momentarily if the size of the file is larger. Some frameworks can be hundreds of kilobytes which is a problem if you’re on a slow connection (think mobile). However, there might be times when it’s necessary to load a JavaScript before the page fully loads. Frameworks like Angular need to be loaded before they can work on the rest of the page:
link JavaScript to HTML example - choice 1
Choice 2: At the very bottom of thetag
If you don’t want to hold up the rest of your page loading, then put the