Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script Tag - async & defer

I have a couple of questions about the attributes async & defer for the <script> tag which to my understanding only work in HTML5 browsers.

One of my sites has two external JavaScript files that currently sit just above the </body> tag; the first is jquery sourced from google and the second is a local external script.

With respects to site load speed

  1. Is there any advantage in adding async to the two scripts I have at the bottom of the page?

  2. Would there be any advantage in adding the async option to the two scripts and putting them at the top of the page in the <head>?

  3. Would this mean they download as the page loads?

  4. I assume this would cause delays for HTML4 browsers, but would it speed up page load for HTML5 browsers?

Using <script defer src=...

  1. Would loading the two scripts inside <head> with the attribute defer the same affect as having the scripts before </body>?
  2. Once again I assume this would slow up HTML4 browsers.

Using <script async src=...

If I have two scripts with async enabled

  1. Would they download at the same time?
  2. Or one at a time with the rest of the page?
  3. Does the order of scripts then become a problem? For example one script depends on the other so if one downloads faster, the second one might not execute correctly etc.

Finally am I best to leave things as they are until HTML5 is more commonly used?

like image 231
Adam Avatar asked May 29 '12 23:05

Adam


People also ask

Apa itu script defer?

Dalam dunia web, Defer memiliki arti sebagai penundaan eksekusi. Script yang diberi Defer sama seperti Async, yaitu didownload pada saat HTML sedang diparse. Bedanya, setelah selesai didownload, script tidak langsung dieksekusi. Script baru dieksekusi dan dijalankan ketika HTML telah selesai di parse hingga 100%.

Apa yang dimaksud dengan script HTML?

HTML adalah singkatan dari Hypertext Markup Language, yaitu bahasa markup standar untuk membuat dan menyusun halaman dan aplikasi web.


1 Answers

This image explains normal script tag, async and defer

enter image description here

  • Async scripts are executed as soon as the script is loaded, so it doesn't guarantee the order of execution (a script you included at the end may execute before the first script file )

  • Defer scripts guarantees the order of execution in which they appear in the page.

Ref this link : http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html

like image 100
Prasanth Bendra Avatar answered Sep 27 '22 19:09

Prasanth Bendra