Using javascript DOM methods, you can attach a new css or javascript file to a page after the page loads or in response to some user action.
This is also a great way to do relatively complex bookmarklets. Instead of encoding a ton of JavaScript carefully into an href attribute value, you can put that code into a file and make a bookmarklet that pulls in the file.
This has advantages over using document.write, which will only work during the time the page is loading.
When you attach the css file, the styles in it will immediately take effect. Likewise, when you add a JS file, any inline javascript in it will execute, and functions and objects will be initialized and become available to other code on the page.
To add css, use the following code:
var cssNode = document.createElement('link');
cssNode.setAttribute('rel', 'stylesheet');
cssNode.setAttribute('type', 'text/css');
cssNode.setAttribute('href', 'yourCssFileNameHere');
document.getElementsByTagName('head')[0].appendChild(cssNode);
To add Javascript, use this:
var scriptNode = document.createElement('script');
document.getElementsByTagName("head")[0].appendChild(scriptNode);
scriptNode.language='javascript';
scriptNode.src=jsFile;
Yes it is a little weird that sometimes you use setAttribute and sometimes you set the attributes using properties. The different browsers like different combinations of these two ways of setting attribute values, and the above combinations work in IE, firefox and Opera.
Dated: 08/04/2006