Note that there are some explanatory texts on larger screens.

plurals
  1. POUse javascript to inject script references as needed?
    text
    copied!<p>I have a JS function that may occasionally get used on some pages. It is dependent on another JS file (swfObject.js), but I'd like to avoid having to include this file all over the place, as thats a wasted request most of the time.</p> <p>Instead, I'd like to create a generic function that can inject a script reference into the page DOM as needed, so if this function is called, it would check for the script, and if it does not exist, load it in.</p> <p>I'm fairly sure this is possible (and I'm not going to use document.write), but before I venture off into uncharted territory, has anyone done this before, and if so, any pointers?</p> <p>EDIT: Ok, I tried it, and it works in IE6 and FF, I haven't tested other browsers yet.</p> <p>Here is my code (Rev 2.0, now with optional callbacks):</p> <pre><code>function loadJSInclude(scriptPath, callback) { var scriptNode = document.createElement('SCRIPT'); scriptNode.type = 'text/javascript'; scriptNode.src = scriptPath; var headNode = document.getElementsByTagName('HEAD'); if (headNode[0] != null) headNode[0].appendChild(scriptNode); if (callback != null) { scriptNode.onreadystagechange = callback; scriptNode.onload = callback; } } </code></pre> <p>and in the method with a dependency:</p> <pre><code>var callbackMethod = function () { // Code to do after loading swfObject } // Include SWFObject if its needed if (typeof(SWFObject) == 'undefined') loadJSInclude('/js/swfObject.js', callbackMethod); else calbackMethod(); </code></pre> <p>Any suggestions?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload