JS takes a lot of time of evaluate
I have a script that I use in many sites.
It's working perfectly except for one site on which the page the script is embedded in loads very very slowly (I don't think it is slow connection-wise, but script-wise).
The thing is this: (I used the timeline in Chrome)
<body> ....
<script...>开发者_开发百科here I load script tag into the head</script>
.. </body>
The HEAD script is loaded after 5 sec. (so this snippet is working well), but its evaluation occurs only after 29 seconds!
Can it be that other scripts are blocking my script's evaluation? Can this be caused because the script is placed in the body and not in the head?
Not blocking but delaying. Yes. If its loaded with scripts and other heavy (for E.A. flash-like) objects this may be the case. Head tag is loaded first so if its in body then it will be processed latter. Read this one: Load and execution sequence of a web page?
If your script is set to run "onload" and the page takes 29 seconds to load, that would cause the delay.
It is actually considered optimal to put script includes at the bottom of your HTML file, which I think is what you've done. Putting scripts in the body tag, rather than the head, should result in an overall faster looking page load.
Update
Here are some references for why you should put scripts at the bottom of your web page...
For performance:
http://developer.yahoo.com/performance/rules.html#js_bottom
For SEO (only really relevant if you have a long section of inline JavaScript):
Allegedly, some search engines only download the first "n" kilobytes of a web page - so you don't want your JavaScript included in that part of the page as it will prevent real content from being indexed.
Google Analytics
Now, Google Analytics is an interesting one. They want you to put the JavaScript at the top of the body for the following reason.
If your page takes 4 seconds to load, putting the Analytics JavaScript at the top of the body means that almost all visits will get logged to Google. If you put the Analytics JavaScript at the bottom of the web page, visitors who arrive on a page and leave again before the page is fully loaded won't get logged.
Example... I arrive on your website looking for information on "Cars" and as soon as the page appears on my screen I see the word "Cars" and click on it. If the Analytics JavaScript is at the top of the page, you will see that I came to the home page and clicked on cars. If you put it at the bottom you will think I arrived directly on the "Cars" page. So for accuracy, you need to put Google Analytics JavaScript right after the opening body tag.
精彩评论