I have a JS function that may occasionally get used on some pages. It is dependent on another JS file (swfObject.js), but I'd like to avoid having to include this file all over the place, as thats a wasted request most of the time.
Instead, I'd like to create a generic function that can inject a script reference into the page DOM as needed, so if this function is called, it would check for the script, and if it does not exist, load it in.
I'm fairly sure this is possible (and I'm not going to use document.write), but before I venture off into uncharted territory, has anyone done this before, and if so, any pointers?
EDIT: Ok, I tried it, and it works in IE6 and FF, I haven't tested other browsers yet.
Here is my code (Rev 2.0, now with optional callbacks):
function loadJSInclude(scriptPath, callback)
{
var scriptNode = document.createElement('SCRIPT');
scriptNode.type = 'text/javascript';
scriptNode.src = scriptPath;
var headNode = document.getElementsByTagName('HEAD');
if (headNode[0] != null)
headNode[0].appendChild(scriptNode);
if (callback != null)
{
scriptNode.onreadystagechange = callback;
scriptNode.onload = callback;
}
}
and in the method with a dependency:
var callbackMethod = function ()
{
// Code to do after loading swfObject
}
// Include SWFObject if its needed
if (typeof(SWFObject) == 'undefined')
loadJSInclude('/js/swfObject.js', callbackMethod);
else
calbackMethod();
Any suggestions?
None of these methods, including document.writing a script tag, work if the script itself has a document.write in it.
If you want your code on the very next line and like to write something like:
There is a smart way to inject script dependencies without the need of callbacks. You simply have to pull the script via a synchronous AJAX request and eval the script on global level.
If you use Prototype the Script.load method looks like this:
If you're using a higher level framework such as JQuery, you could check out the
$.getScript(url, callback)
function.Consider using require.js. This might need some rework of your frontend framework, but it's totally worth it. With require, you could just do the following in your
fileUsedOccasionally.js
:Checkout the YUI Loader utility. It's super handy, unobtrusive javascript for loading scripts on-demand.
Here's a link to an example using non-YUI scripts:
http://developer.yahoo.com/yui/examples/yuiloader/yl-addmodule.html
I wrote a simple module that automatizes the job of importing/including module scripts in JavaScript. Give it a try and please spare some feedback! :) For detailed explanation of the code refer to this blog post: http://stamat.wordpress.com/2013/04/12/javascript-require-import-include-modules/