Monday 15 December 2008

Loading an external JS or CSS file on the fly.

OK all you dev's out there are prob used to loading JS or CSS somewhere in your HTML this is generally hard coded and is something like this
[head]
[script type='text/javascript'm src='loadofstuff.js'][/script]
[/head]


However there may come a time when you want to bring in a JS file based on some criteria or process that is only resolvable at runtime. Localization for example, you want to bring in a JS file that has your lovely code rendered in glorious Polish or Tagalog or you need to change the CSS to facilitate Hebrew right to left alignment.

To do this you need to have some insertion fun with the DOM. Nothing like a good insertion if it is done well I always say!

For JS you would create a "script" element and for CSS you would create a "link" element .. yes it is that simple ... here is some code


function insertMyFile(whatIsIt,whatsTheFile)
{
if(whatIsIt == "js")
{
externalFile = document.createElement("script");
externalFile.setAttribute("type","text/javascript")
externalFile.setAttribute("src",whatsTheFile)
} else if(whatIsIt == "css")
{
externalFile = document.createElement("link");
externalFile.setAttribute("rel", "stylesheet")
externalFile.setAttribute("type", "text/css")
externalFile.setAttribute("href", whatsTheFile)
} else {
alert("You knob! Pass a file type please");
}
if (typeof externalFile!="undefined")
{
document.getElementsByTagName("head")[0].appendChild(externalFile);
} else {
alert("Bollox something nasty has happened");
}
}


Then all you need to do at some point in your code is go...
insertMyFile("js","myPolishCode.js")
or
inserMyFile("css","myHebrewCss.css")

Okey Dokey?

Disqus for Domi-No-Yes-Maybe