I have a couple of questions about the attributes async & defer for the 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
tag; the first is jquery sourced from google and the second is a local external script.
Is there any advantage in adding async to the two scripts I have at the bottom of the page?
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 ?
with the attribute defer the same affect as having the scripts before ? If I have two scripts with async enabled
Finally am I best to leave things as they are until HTML5 is more commonly used?
Answer
Keep your scripts right before . Async can be used with scripts located there in a few circumstances (see discussion below). Defer won't make much of a difference for scripts located there because the DOM parsing work has pretty much already been done anyway.
Here's an article that explains the difference between async and defer: http://peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/.
Your HTML will display quicker in older browsers if you keep the scripts at the end of the body right before . So, to preserve the load speed in older browsers, you don't want to put them anywhere else.
If your second script depends upon the first script (e.g. your second script uses the jQuery loaded in the first script), then you can't make them async without additional code to control execution order, but you can make them defer because defer scripts will still be executed in order, just not until after the document has been parsed. If you have that code and you don't need the scripts to run right away, you can make them async or defer.
You could put the scripts in the tag and set them to defer and the loading of the scripts will be deferred until the DOM has been parsed and that will get fast page display in new browsers that support defer, but it won't help you at all in older browsers and it isn't really any faster than just putting the scripts right before which works in all browsers. So, you can see why it's just best to put them right before .
Async is more useful when you really don't care when the script loads and nothing else that is user dependent depends upon that script loading. The most often cited example for using async is an analytics script like Google Analytics that you don't want anything to wait for and it's not urgent to run soon and it stands alone so nothing else depends upon it.
Usually the jQuery library is not a good candidate for async because other scripts depend upon it and you want to install event handlers so your page can start responding to user events and you may need to run some jQuery-based initialization code to establish the initial state of the page. It can be used async, but other scripts will have to be coded to not execute until jQuery is loaded.
No comments:
Post a Comment