I’ve been doing a lot with web optimization recently, and I’ve come across an interesting problem. I was wondering if anyone might know of an existing solution.
Say you have multiple, page specific external .js files, each with it’s own page specific
$(document).ready() function. Say the document ready function for page 1 applies a style to every <li> in the body, while the document ready in page 2 only styles <input type="button" />s. Just a simple example.
Now say you bundle these 2 scripts, along with all your library scripts, to reduce the number of http requests on page load. Now, both document ready’s will fire, and the li’s on page 2 will be formatted with the code meant only for page 1.
My question is this – Is there a way through either jQuery or a third party library to assign a specific document ready to a specific page but still have them all bundled into one .js file?
From an architectural point of view, if the block of code is only meaningful on one page, why shouldn’t it be bundled with that page? I know it may seem more “organized” to put all of your HTML in one place and your javascript in another, but is it really saving your server or speeding up your user experience?
There comes a point with bundling when we reduce the number of connections, but increase the load on the server because we are stuffing so much unused junk into our combined file. Which is better serving 1,000 1k files or 100 100k files. If you have 100 pages each with a unique
document.readythen you’re adding a lot of data for a user when they only visit one page. The benefit of such a bundle is really only useful if there is a high probability the user will use some of the bundled content. Example would be Google.com, where they pre-cache entities needed in the results page, since by the very fact you are AT google.com implies with a pretty high degree of certainty you will do a search. It does not pre-cache gmail, or google docs though.