javascript tutorial - [Solved-5 Solutions] <script> tags in HTML markup - javascript - java script - javascript array



Problem :

Where should we put <script> tags in HTML markup ?

Solution 1:

Here's what happens when a browser loads a website with a <script> tag on it:

  • Fetch the HTML page (e.g. index.html)
  • Begin parsing the HTML
  • The parser encounters a <script> tag referencing an external script file.
  • The browser requests the script file. Meanwhile, the parser blocks and stops parsing the other HTML on your page.
  • After some time the script is downloaded and subsequently executed.
  • The parser continues parsing the rest of the HTML document.

Solution 2:

<!-- index.html -->
<html>
    <head>
        <title>My Page</title>
        <script type="text/javascript" src="my-script.js"></script>
    </head>
    <body>
        <div id="user-greeting">Welcome back, user</div>
    </body>
</html>
click below button to copy the code. By JavaScript tutorial team

Javascript:

// my-script.js
document.addEventListener("DOMContentLoaded", function() { 
    // this function runs when the DOM is ready, i.e. when the document has been parsed
    document.getElementById("user-greeting").textContent = "Welcome back, Bart";
});
click below button to copy the code. By JavaScript tutorial team

Solution 3:

The modern approach

Today, browsers support the async and defer attributes on scripts. These attributes tell the browser it's safe to continue parsing while the scripts are being downloaded.

async

<script type="text/javascript" src="path/to/script1.js" async></script>
<script type="text/javascript" src="path/to/script2.js" async></script>

click below button to copy the code. By JavaScript tutorial team

Solution 4:

Non-blocking script tags can be placed just about anywhere:

<script src="script.js" async></script>
<script src="script.js" defer></script>
<script src="script.js" async defer></script>
click below button to copy the code. By JavaScript tutorial team
  • async script will be executed asynchronously as soon as it is available
  • defer script is executed when the document has finished parsing
  • async defer script falls back to the defer behavior if async is not supported

Such scripts will be executed asynchronously/after document ready, which means cannot do this:

<script src="jquery.js" async></script>
<script>jQuery(something);</script>
<!--
  * might throw "jQuery is not defined" error
  * defer will not work either
-->

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - <script> tags in HTML markup