Saturday, March 31, 2012

Dynamically loading a JavaScript file that dynamically loads a CSS file in an HTML page

UPDATE 2012-06-12 Also check out the the follow-up on this post.
The title of this post may look rather impressive. Until now, I didn't even know whether it was possible: loading a file dynamically in JavaScript that loads another file dynamically. Why the heck would I want to do that? I will describe the answer shortly.
First: It is possible to dynamically load a JavaScript file into an HTML page. Here is the code:
// Get a reference to the HEAD element of the HTML page.
// document.head is more efficient but only works in HTML5.
var head = document.head || document.getElementsByTagName('head')[0];
// Dynamically add a JavaScript source to the HEAD element.
var scriptEl = document.createElement('script');
scriptEl.type = 'text/javascript';
scriptEl.src = 'dynamic.js';
head.appendChild(scriptEl);
Second: It is possible to load a CSS file dynamically into an HTML file, using the following JavaScript:
// Get a reference to the HEAD element of the HTML page.
// document.head is more efficient but only works in HTML5.
var head = document.head || document.getElementsByTagName('head')[0];
// Dynamically add a CSS reference to the HEAD element.
var linkEL = document.createElement('link');
linkEl.type = 'text/css';
linkEl.rel = 'stylesheet';
linkEl.href = 'dynamic.css';
head.appendChild(linkEl);
Now for the reason I want to combine the two techniques. I am writing an HTML5 bookshelf app that reads HTML5-formatted book files into an iframe. I do not control the content of those books. They are uploaded to the 'shelf' by the app users. However, I want a JavaScript to act on the content of a book file like it was included by the HTML file itself in the following way:
<script type="text/javascript" src="dynamic.js" ></script>
The script (among many other things) attaches CSS class names and styles to the elements in the book file. For that purpose it needs to link a CSS file to the HTML page like it was included by the HTML file itself in the following way:
<link type="text/css" rel="stylesheet" href="dynamic.css" />
To dynamically load a JavaScript file that loads a CSS file, use the first code example above and put the second code block (that links to the CSS) in the file dynamic.js. Note that it is rather difficult to know when the JavaScript and CSS files (especially the latter) have been fully loaded. Since this is also a requirement in my bookshelf project, it will be the subject of a future blog post.

No comments:

Post a Comment