views:

451

answers:

4

Duplicate of: http://stackoverflow.com/questions/203113/use-javascript-to-inject-script-references-as-needed

Javascript doesn't have any directive to "include" or "import" another js file. This means that if script1.js uses functions/objects defined in script2.js, then every html page that includes script1.js must include script2.js before it.

This shouldn't be a big problem if you only have 2 js files in like 10 html pages. I mean, it's manageable then!

But say suddenly you change script1.js and improve it by using functions/objects defined in a new file, script3.js
The problem is, you can't just tell script1.js to include script3.js, instead, you have to remember every html file that included script1.js and update it to include script3.js as well!

This seems like rather stupid way of organizing code.

Are there recommended strategies or practices to deal with this issue?

Would it be acceptable to have a gigantic js file that holds all the functionality that you use across the website?

A: 

I guess you could use document.write in your JS files to make sure they include whatever dependencies they're dependent upon, though I wouldn't really recommend it...

Thomas Hansen
+1  A: 

Scriptaculous (and probably other frameworks) handle this by writing script tags for the included files to the document when they are loaded. Below is the relevant bit from the scriptaculous.js file that allows loading the other files in the framework.

 var Scriptaculous = {
   Version: '1.8.2',
   require: function(libraryName) {
     // inserting via DOM fails in Safari 2.0, so brute force approach
     document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
   },
   ...
tvanfosson
A: 

Personally I try to avoid all this confusion by rolling all my javascript into one file. If there's one page which requires a LOT of javascript which the other pages don't need, then just have two files - generally the page-specific JS can be loaded after the generic js without hassles anyway.

To roll the JS files into one, I use Dean Edwards's Javascript Packer, combined with a helper script that I described on my blog. It makes working with many JS files muuuuuch easier (for me at least), and the compression you get from packing the javascript is better.

nickf