Skip to content

Instantly share code, notes, and snippets.

@geniuswebtools
Created January 10, 2012 12:59
Show Gist options
  • Save geniuswebtools/1588969 to your computer and use it in GitHub Desktop.
Save geniuswebtools/1588969 to your computer and use it in GitHub Desktop.
Import JavaScript files like you would your CSS files.
/*
Directions:
1. Place all of your JavaScripts in the same folder as
this one, or resolve the path to match the scriptURI var.
2. Add the filenames of the JavaScripts you want to load
automatically as a comma seperated list of arguments
in the gLoadJS function call.
3. Link this JavaScript file to your HTML document, and
give add the id="importJSURI" to the script tag.
<script type="text/javascript" src="/scripts/import.js" id="importJSURI"></script>
4. Open the browser JS console and look at the log messages
to confirm the file was loaded and which path was used.
Note:
If you forget to add the ID attribute to the script tag
for the import.js file, it will still loop to find it,
but it'll be faster if you include the ID
*/
// Modify these arguments to load the required JS files for each page load.
gLoadJS('script1.js','script2','script3');
// Do NOT edit below this line
function gConsole(msg)
{
// Attempt to add data to JS Console log.
try { console.log(msg); }
catch(e) { /* Browser has no console object */ }
} // end gConsole
function gLoadJS()
{
// Are there JS files to import?
var jsFiles = gLoadJS.arguments;
if(jsFiles.length == 0)
{
gConsole('gLoadJS() was called with no scripts to load. :`(');
return false;
}
// Attempt to import JS files
scriptPath = scriptURI = false;
try { scriptPath = document.getElementById('importJSURI').src; }
catch(e)
{
var allScripts = document.getElementsByTagName('script');
for(i=0; i<=(allScripts.length-1); i++)
{
scriptPath = allScripts[i]['src'];
if(scriptPath.indexOf('import.js') >= 0) { break; }
}
gConsole('gLoadJS() found the scriptPath by using a loop, you should add the ID to this page. See the import.js file for directions.');
}
scriptURI = scriptPath.replace(/import\.js/gi, '');
gConsole('Script URI: ' + scriptURI);
if(!scriptURI)
{
gConsole('No script URI path found for importing JavaScripts :(.');
return false;
}
for(i = 0; i <= (jsFiles.length - 1); i++)
{
try
{
document.write('<scr' + 'ipt type="text/javascript" src="' + scriptURI + jsFiles[i] + '">/* Loaded by gLoadJS() */</scr' + 'ipt>');
gConsole('gLoadJS() added script `' + scriptURI + jsFiles[i] + '` to DOM.');
}
catch(e) { gConsole('gLoadJS() encountered an error loading `' + scriptURI + jsFiles[i] + '`'); }
}
} // end gLoadJS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment