Learn how to incorporate JavaScript code onto a website using the script tag.
While HTML and CSS are useful when styling and structuring our websites, they offer limited capabilities when building complex and interactive websites. In order to build complex websites, other programming languages that allow storing and manipulation of data and variables must be included. Luckily, HTML offers a way for programmers to include other programming languages onto a website using HTML.
The <script>
tag is an HTML tag that offers a way to include JavaScript code within webpages. The script
tag can be added to a webpage by including the tag at the bottom of the page’s body
:
To add JavaScript to the webpage, it must be written in between the opening and closing script
tags:
The script tag can also be used to execute code from external script files. The src
attribute points to the URL where the external script is located, and executes the script when the webpage parses the script tag.
The website below offers an example of this practice in action. The website has a script tag that points to the external-script.js
file. When the webpage is run, the code in the external script will execute:
The use of the script tag for this purpose is central to the computer science principle of abstraction. Abstraction allows programmers to use libraries and scripts that others have developed, even if they aren’t fully able to understand how the script works.
The order in which a script is executed impacts its functionality, and whether other scripts are able to access functions and methods that are written in the script. If a script utilizes a function from another script, then the script that contains the function definition must execute before the reliant script.
The following example should have the same functionality as the example from before, except that the external-script
file has been split so that the function prompting the user for their name is separate. As is currently written, the webpage doesn’t work. This is caused by the fact that the script containing the name prompt is loaded after the file that uses the function. If the order of the two scripts were changed, then the webpage would work as intended.