When it reads the line alert("hello") it can see we want to display the word “hello” in an alert:
The script tag has some attributes that we can use. These are:
Now that we have an external script we can look at some of the other script attributes. Let's start with async and defer.
When the browser finds a script tag in the HTML the page loading stops while the browser fetches the script. Once the file is ready the browser runs the code. Once the code has finished running the page will resume loading.
async and defer will improve web performance by allowing the page to continue to load. But they do it in different ways.
Let's look at async first.
The async attribute tells the browser to download the file in the background. This allows the page to continue loading. As soon as the file has downloaded the browser will run the code.
How does defer differ? This attribute tells the browser to download the file in the background like async. Yet, it will only run the code once the browser has finished processing loading the page.
This means that defer will not block the page at all. Whereas, async will only block the page when it runs the code. Both attributes mean that they will not block the page when the script is downloading.
The general rule is that you should use defer because it will never stop the page from loading. Also, if you have more than one script on the page defer will run them in order. With async the code runs as soon as they download and you cannot guarantee order.
There is one more attribute that we have not talked about. It is the charset attribute.
This attribute allows you to specify the encoding of the characters. Which can either be “UTF-8” or “ISO-8859-1”. In 20 years of creating web sites, I have never used this attribute. It is safe to say you can leave the default which is “ISO-8859-1”.
Where should you put your script tags? The general rule is to add them before the </body> tag. This is at the end of the page and means that most of the page has loaded.