I try to optimize my pages by putting some async attributes on my scripts. It seems to break my javascript since $(document).ready is executed before the all scripts are loaded!
I saw that I can resolve my problem by putting $(window).load instead of $(document).ready but I was wondering if there is a better solution.
This solution trigger 2 problems in my case :
- I have to change all
$(document).readyand tell all the developpers to not use it anymore - The scripts will be executed after all images are loaded. My website has a lot of heavy images and I really need some scripts to be executed ASAP after dom is ready.
Do you have some magic tricks? Maybe putting all scripts at the end? use defer instead of async?
After some extensive research, I can definitely say that putting scripts at the end of the page is THE best practice.
Yahoo agrees with me : http://developer.yahoo.com/performance/rules.html#js_bottom
Google don’t talk about this practice and seems to prefer async scripts : https://developers.google.com/speed/docs/best-practices/rtt#PreferAsyncResources
IMHO, putting script at the end of the page has several benefits over async/defer:
$(document).readyor$(window).loadThe only drawback that I can see is that the browser won’t be able to parallelize the downloads.
One good reason to use async/defer instead is when you have a script that is completly independant ( do not need to rely on the execution order) and that don’t need to be executed at a specific timing. Example : google analytics.