Royi Namir
Royi Namir

Reputation: 148524

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) ?

Upvotes: 5

Views: 1218

Answers (2)

Bergi
Bergi

Reputation: 664484

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.

Upvotes: 1

Ramesh
Ramesh

Reputation: 13266

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

Upvotes: 4

Related Questions