Efficiently load JavaScript with defer and async

0 Shares
0
0
0
0
0
0
0

With HTML5, we get two new boolean attributes for the 

hello world

The console output: script1 is running at 1496747869008 script1.js:4 script1 element null script1.js:8 script1 finishes running at 1496747870008 script2.js:2 script2 is running at 1496747870009 script2.js:4 script2 element null script2.js:8 script2 finishes running at 1496747872009

Conclusion:

  • When we open the html in the browser, we can notice the delay of page load. The page goes blank before it renders correctly. This is due to the fact that the running of the two scripts blocks the DOM rendering.
  • When scripts are running, they are not able to fetch the DOM element (i.e. document.getElementById(‘load-experiment’) being null). This is because scripts are run before DOM is rendered.
  • Scripts themselves are blocking each other. They are run in the order specified in the html. Script2 is run after script1 finishes running.

Put script tags at the bottom of the body



    
         test js tag async and defer attributes
    
    
        

hello world

The console output: script1 is running at 1496751597679 script1.js:4 script1 element

​ hello world ​

​ script1.js:8 script1 finishes running at 1496751598679 script2.js:2 script2 is running at 1496751598680 script2.js:4 script2 element

​ hello world ​

​ script2.js:8 script2 finishes running at 1496751600680

Conclusion:

  • No page delay and blank page when opening the page in browser, as scripts are put/run after the DOM is ready.
  • Scripts can correctly fetch DOM elements.
  • Scripts themselves are blocking each other, as the same as the first example.

Conclusion

The general rule to import script is:


    
        
        
    
    
        
        

hello world

Code Sample: https://github.com/n0ruSh/the-art-of-reading/tree/master/javascript/Async%20Javascript/defer-async

Reference