Tuesday, November 24, 2009

Loading Javascript libraries on demand

I needed to load the Google visualization API, but only needed it under certain conditions. Not wanting the overhead if not needed, I looked around for a way for Javascript to include external libraries. Sadly, it appears this facility is lacking, so I came up with the following hack.

// create the script element with no src set
<script language="Javascript" type="text/javascript" id="google_jsapi"></script>
...
// add the src to the script element
if ( some_condition ) {
document.getElementById('google_jsapi').src = 'http://www.google.com/jsapi';
}
...
// use the library
window.onload = do_stuff();

No comments:

Post a Comment