No matter how awesome your JavaScript code is, we all face the same problem: how to squeeze it down the wire and get it loaded and running in the browser as quickly and efficiently as possible. There are about as many ways to approach this problem as there are developers trying to solve it, which makes the landscape of JavaScript Loading solutions confusing and painful to navigate. But it doesn't have to be so ugly. We're gonna break it down so you can come away feeling more confident in how best to load your JavaScript. Several common strategies will be covered, including:
- Build-time versus on-the-fly
techniques
- Code organization/compression
(minification, gzip, etc)
- File concatenation
- Inline scripts
- Dynamic parallel loading of
JavaScript resources (LABjs, etc)
- Cache optimization (initialization
profiling, on-demand loading,
pre-fetching, etc)
7. How To Suck At Loading JavaScript 1. Load too many files 2. Load too few files 3. Load all files before DOM-ready 4. Use the <script> tag 5. Load all files serially
8. Relax! I’m not gonna keep telling you how much you suck. And you don’t suck, JavaScript loading sucks .
9. How To NOT Suck At Loading JavaScript 1. Use a build-process for local scripts 2. Use g-zip and minifiers 3. Profile, load when needed 4. Load parallel, execute serially 5. Load now, execute later
26. It gets crazy when you look at ie6, ie7, ie8, opera, chrome, safari…& mobile Hint: This Sucks And it gets even crazier when you load other page elements like css near your <script> tags
28. Put simply, LABjs is intended to be a simple way to replace <script> tags with a mechanism that gives you more control over loading and execution behavior.
29. LABjs is a script loader that lets you load *any script, into any page, at any time. It uses an expressive API that helps you replace your script tags easily. *exceptions explained in a moment.
30. When NOT to use LABjs 1. If your script uses document.write 2. If your script ITSELF does unsafe DOM-ready detection – does not apply to scripts that use the results of such detection.
31.
32. FF3 with <script> & <img> tags FF3.5 with <script> & <img> tags LABjs in every browser
33. 16.84 seconds vs. 6.24 seconds 2.7x speed increase in overall page load Enough said, right?
34. The LABjs API is a chaining API (similar to jQuery), which you can use to express one or more groups of scripts to load, where (by default) all scripts will load in parallel, but groups will execute in serial. You can specify as many independent chains as necessary. So, you can both load scripts that have no dependencies on each other (and thus can run in parallel), and those scripts that do have execution order dependency, while still loading everything as quickly as possible.
41. Only the part of the decision matrix that works on-demand at any point in the page lifetime, for same- and cross-domain scripts, loading in parallel, ensuring execution order dependencies, allowing coupling.