<script> tag. When
<script> tags are in the flow of an HTML document, the browser must stop rendering and wait for the script file to download and execute before continuing (example). Creating a new
The best technique
<script>tag at the bottom of the page, just inside the
- Create a second
That’s a tiny amount of code to get your bootstrapped so it will load incredibly fast (especially when gzipped).
The actual code on your page ends up looking like this:
You’ll note that I mentioned the best practice of placing this code towards the end of the page, just inside the closing
</body> tag. This is advice that has been around for a while and I still recommend it, even when using this technique. The reason is that you’re guaranteed all of the DOM elements you may need are already present on the page. Loading your scripts earlier could introduce timing issues where you would need to worry about using
window.onload or some other method to determine when the DOM is ready to be used. By including this code at the bottom of the page, you are assured that the DOM is ready to be poked and you won’t need to delay initialization any further.
Inlining the first script
YUI 3 has you covered
YUI 3 is designed around this very premise. You can start by just loading the yui.js file and then use the built-in Loader component to dynamically load the rest of the YUI library. For example:
This code loads in the YUI “seed” file first, then creates a new instance of the
Update (1-Aug-2009): Added section on script placement to clarify why I do it in
<body> instead of
Disclaimer: Any viewpoints and opinions expressed in this article are those of Nicholas C. Zakas and do not, in any way, reflect those of my employer, my colleagues, Wrox Publishing, O'Reilly Publishing, or anyone else. I speak only for myself, not for them.
Both comments and pings are currently closed.