Include JavaScript Files with JavaScript
As always, I’m constantly looking for ways to speed up my coding, to keep files scalable and manageable. Here’s a tip that will let you `import` your external JavaScript files much like you would `import` your external CSS files (, but that’s different post.)
No, we can’t literally import our JavaScript like CSS, but the concept is the same. We can link to one JavaScript file and have it include additional JavaScript files for us, and here’s how we do that.
Create a file called `import.js`, and call the import.js file as your first <script> tag in the <head>. Copy the code below and paste it inside of the import.js file.
1 2 3 4 5 6 7 8 9 10 11 12 | var incScripts = new Array('ft_validate.js','swfobject.js','jquery.js'); var allScripts = document.getElementsByTagName('script'); for(s=0; s<=(allScripts.length-1); s++) { var scriptPath = allScripts[s]['src']; if(scriptPath.indexOf('import.js') >= 0) { scriptURI = scriptPath.replace(/import.js/gi, ''); for(i=0;i<=(incScripts.length-1); i++) { document.write('<script type="text/javascript" src="' + scriptURI + incScripts[i] + '"></scr' + 'ipt>'); } break; } } |
On line 1 change the JavaScript file names to those you want to include in the web page using our new import.js file. These files are assumed to be in the same folder as import.js.
Note: If you want to include a JavaScript file in another folder just make sure you add the missing path data with the file name relative to the location of the import.js file. So if you need to include a file in the folder above your incScripts may have a value like this:
1 | var incScripts = new Array('../ft_validate.js','swfobject.js','jquery.js'); |
I tested this in MSIE, Firefox, Chrome & Safari (all windows), and didn’t have any problems w/ any of the browsers.
