It's oft recommended optimization to consolidate your javascript into fewer parts and reduce the number http requests. On a smaller site you could easily arrive at structure like:
/js/jQuery-xx.js
/js/plugins.js
/js/app.js
Even in a modest site (with just some jQuery polish) that app.js
can get pretty heavy. For organization it's easy to break apart the implementations into logcal bits:
..
/js/app-global.js
/js/app-contact.js
/js/app-products.js
/js/app-splash.js
Now as separate files it's trivial to require them for a specific context, though their individual sizes are quite small, around 1–3 kb a piece, so it occurs to me it'd be pretty smart to recombine them back into a single file simply served as app.js
.
But it occurs to me that in app.js
file with about 20 or so jQuery selectors and misc javascript that goes unused on most pages. Seems like wasted CPU cycles to have these jQuery selectors firing when they target elements that don't exist in most contexts.
Which is the more pressing optimization: • reducing http requests? • reducing unused jQuery selectors?
I'm using Chrome's Audit tool to profile and it recommends fewer network request for javascript files. Any guidelines for measuring bloat in jQuery.ready(…);
?
Update
Weighing the evidence presented the simplest thing to do is to serve the implementation code as a single file and then activate different modules using a routing system. In my case I just hooked into the simple php router that I've already built:
root.php
<script type="text/javascript">
var myApp = {
modules: {}
bootstrap: function()
{
<?php
if ( $pageId == 'contact' )
echo 'myApp.modules.contact();';
if ( $pageId == 'index' )
echo 'myApp.modules.splash();';
if ( preg_match( '~^help/~iu', $pageid ) )
echo 'myApp.modules.faq();';
?>
}
}
</script>
<script type="text/javascript" src="/js/jquery1.9.1.js"></script>
<script type="text/javascript" src="/js/jquery-plugins.js"></script>
<script type="text/javascript" src="/js/myApp.js"></script>
myApp.js
$(document).ready(function()
{
myApp.bootstrap();
//… global jQuery stuff …
});
// Define modules
myApp.modules.splash = function() {
$('#splash').click(
//…etc…
);
}
myApp.modules.faq = function() {
$('.faq').show(
//…etc…
);
}
myApp.modules.contact = function() {
$('.contact').bind(
//…etc…
);
}