Christian Heilmann

Conditional loading of large Javascript files

Wednesday, February 16th, 2005 at 2:11 pm

You may sometimes find yourself with big Javascript libraries to include in your documents. Currently I am on a project where one of them is about 1MB big (don’t ask).
Now, I wondered what can be done to only apply these when they are really needed, and the answer, aside from adding an extra page to the process is to add them dynamically via the DOM:

if(!document.getElementById || !document.createElement){return;}
var newjs=document.createElement(‘script’);

This example would only load the file “functions.js” when DOM is available in the browser, older browsers would not load the file.

Share on Mastodon (needs instance)

Share on Twitter

My other work: