Let’s see three of them step by step;
You are not restricted to be maintaining identical code in multiple HTML files. However,
This is useful if you want the same scripts available to multiple documents. It saves you from repeating the same task over and over again, and makes your website much easier to maintain.
<script> tag and its
script.js and place the following code in it:
This as expected will show Hello Sunil on the page.
<script src="script.js"></script> <script src="script_new.js"></script>
The way we have loaded our script above is an example of a normal loading.
- Normal loading
- Asynchronously loading
- Defer its loading
Once the execution finishes the browser will continue parsing the rest of the HTML file.
When we want to load a script file asynchronously we just need to add the word
<script src="script.js" async></script>
Defer its loading
To defer the loading we just need to add
defer to the reference.
<script src="script.js" defer></script>
Placing scripts in external files has multiple advantages:
- Separate files makes maintenance easier
- If you are using the same scripts in different HTML files, including an external file prevents repetitive code.
<script> tag indicates the browser that the contained statements are to be interpreted as executable script and not HTML. Here’s an example:
Now when we open this page we are going to see Hello Sunil.
The next million-dollar question is – Shall we put the
<script> tags in the
<body> section of the HTML?
<script> tags can actually be put into both sections. But please take note that there is a difference where you put them and the order of the scripts does matter.
- We place the critical scripts at the top.
We are sorry that this post was not useful for you!
Let us improve this post!
Tell us how we can improve this post?