Monday, March 17, 2014

The <script> element

The unobtrusive javaScript programming paradigm

Unobtrusive JavaScript is an approach to web programming that supports separation of behaviour (JavaScript code), structure (HTML code) and presentation (CSS code).
According to this programming paradigm, to accomplish separation is best to write all your JavaScript in an external file and embed it in HTML document using a <script> element with src attribute.

The <script> element is synchronous by default

Let's examin how the <script> element allow you to insert javascript in a HTML document.
<script src="scripts/javascript_app.js"> </script> <!--synchronous script-->

When JavaScript engines encounters a <script> element, they stop parsing HTML to download and interpreter the JS file, then they resume parsing and rendering HTML.

The <script> element has two important attribute: HTML 4.1 defines the async attribute and HTML5 introduces the defer attribute. These two attributes cause scripts to be executed differently, in browsers supporting them.

The <script> element's defer attribute

<script src="scripts/javascript_app.js" defer> </script> <!--deferred script--> 

When browsers find a defer attribute they continue parsing HTML document and, at same time, downloads the JavaScript file, but the execution of the JS is deferred after the HTML rendering.

The <script> element's async attribute

<script src="scripts/javascript_app.js" async> </script> <!--asynchronous script-->

The async attribute signals browsers to continue parsing HTML document and to start downloading and executing the JS file immediately.

Note that async and defer attributes were first supported by IE10.

Where to place the <script> element in your page ?

When it came to decide where to place the script element, it must be considered the LOAD SPEED of a page that is the result of the time consumed for downloading all the resources linked to the page.

  • in the head: avoid this location, the script makes seem the page slow to load and your script has to wait for load or DOMContentLoaded events
  • in the page: only place the script element here, if you use the document.write() method
  • before the closing </body> tag: this is the best location, because the script does not block loading and DOM has already been created.

No comments :

Post a Comment