Javascript - JavaScript in HTML Deferred Scripts


You can use an attribute named defer for the <script> element.

defer indicates that a script won't be changing the structure of the page as it executes.

The script can be run safely after the entire page has been parsed.

Setting the defer attribute on <script> element signals to the browser that download should begin immediately but execution should be deferred:

<!DOCTYPE html> 
    <title>Example HTML Page</title> 
    <script type="text/javascript" defer src="example1.js"></script> 
    <script type="text/javascript" defer src="example2.js"></script> 
    <script type="text/javascript" defer src="example.js"></script>     
    <!-- content here --> 

Even though the <script> elements are included in the document <head>, they will not be executed until after the browser has received the closing </html> tag.

The defer attribute is supported only for external script files.

The browsers that support the HTML5 implementation will ignore defer when set on an inline script.

For XHTML documents, specify the defer attribute as defer="defer".