Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - To combine or not combine, that is the question

Ok, so I know that it's obvious to combine all of a pages Javascript into a single external file for efficiency purposes, but that's not quite the question here.

Say I have Default.htm with a search field that has a little Javascript magic attached to it. Then I have Contact.htm with a contact form that has some Javascript magic attached to it. And finally I have a FAQ.htm with some jQuery panels showing the answers... you get the picture.

Basically I have three pages that all have "some" javascript need, but none of the Javascript is used on any other pages.

Is it better to combine all of that Javascript into one big minified file that loads once and is then stored in Cache, or is it better to use an individual Javascript file on the Default page, but not use it on the Contact page... etc?

What works best in this scenario?

Option: 1

Default.htm
jquery.js
default.js

Contact.htm
jquery.js
contact.js

Faq.htm
jquery.js
faq.js

Option: 2

Default.htm
jquery-default-contact-faq-min.js

Contact.htm
jquery-default-contact-faq-min.js

Faq.htm
jquery-default-contact-faq-min.js

PS: for all you asp.net guys, I'm using Combres to Combine, Minify, and Version my Javascript files

like image 607
Chase Florell Avatar asked Sep 07 '10 04:09

Chase Florell


2 Answers

I would definitely vote to combine them. If you are concerned about parse or setup time for the "not used" Javascript, then I would recommend structuring your Javascript with each file in a closure, and then run the closures you need on the pages you need them. For example:

// File 1
window.closures = window.closures || {}
window.closures["page1"] = (function() {
  // Javascript for Page 1
});

// File 2
window.closures = window.closures || {}
window.closures["page2"] = (function() {
  // Javascript for Page 2
});    

// File 3
window.closures = window.closures || {}
window.closures["page2"] = (function() {
  // Javascript for Page 2
});

Then, in your page:

<!-- This one combined.js file will be downloaded once and cached //-->
<script type="text/javascript" src="combined.js"></script>
<script>
  // Run the Javascript in your combined.js intended for page2
  window.closures["page2"]()
</script>
like image 162
Chris Heald Avatar answered Sep 23 '22 08:09

Chris Heald


combine into 1 file. let it get cached. it loads once on any page, and for any subsequent pages it can use the cached copy.

like image 32
Moin Zaman Avatar answered Sep 19 '22 08:09

Moin Zaman