JavaScript-for-Web-Developers

Book notes for Professional JavaScript for Web Developers, 4th Edition By Matt Frisbie

View project on GitHub

Chapter 2. JavaScript in HTML

HTML recognizes javascript from the <script> tag. The code contained in a script block is interpreted from top to bottom, and unless the tag is importing a file denoted with the defer or async attribute, the page will not continue rendering until after the script’s code has finished executing.

The defer attribute indicates that a code block can safely be executed after the documents content has been parsed and displayed.

The async attribute indicates that a code block can be downloaded immediately, but that it should not impact the content of the page and therefore should not prevent other actions from taking place. “Using async scripts also confers to your page the implicit assumption that you do not intend to use document.write.”

Because of the synchronous nature of code execution, most non-SPA website now include all JavaScript at the tail-end of the body tag, after the page’s visible content.

<script><!-- console.log('hi!') --></script> is valid and interpreted correctly. This is legacy from the browser Mosaic, which would interpret script tags as HTML and display their content on the page

The <noscript>tag contains the HTML you’d like rendered to the page in the event that the browser does not support or has JavaScript disabled.