Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript [defer] attribute and document.ready?

After reading about the defer attribute at mdn

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed.

It looks nice.

So I've tested it against $(function () { }); and $(window).load(...)

<script>
$(function ()
{
  alert('1')
});
$(window).load(function ()
{
  alert('2')
});
</script>

<script defer="defer">
  alert('4');
</script>

This code Always output 4,1,2 !

Ok So now I can recognize the time where the document is parsed.

In what scenarious will i need the stage before document.ready (where the parse time complete) ?

like image 302
Royi Namir Avatar asked Oct 09 '12 15:10

Royi Namir


2 Answers

From MDN

The defer attribute shouldn't be used on scripts that don't have the src attribute

The actual use would be that you can still have scripts at the top of the page and make the browser load them after the entire page is parsed fully thus improving the client side of the performance.

From YSlow

The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering

like image 55
Ramesh Avatar answered Oct 12 '22 09:10

Ramesh


Check out the W3 HTML spec:

The async and defer attributes are boolean attributes that indicate how the script should be executed. The defer and async attributes must not be specified if the src attribute is not present.

So, this attribute is only valid for external scripts.

like image 32
Bergi Avatar answered Oct 12 '22 07:10

Bergi