Skip to content

Instantly share code, notes, and snippets.

@kentbrew
Created February 26, 2011 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kentbrew/845405 to your computer and use it in GitHub Desktop.
Save kentbrew/845405 to your computer and use it in GitHub Desktop.
Safe Script Tag Insertion
// When a script appends new SCRIPT tags to the HEAD or BODY, it can
// run into serious trouble. If it was originally included in the HEAD, the
// HEAD might not have fully rendered when it fires, and the BODY isn't there yet.
// And if it's in the BODY, older browsers may blow chunks if it tries to append
// SCRIPT tags to the HEAD.
//
// What seems to work: be HEAD/BODY agnostic. Look for the first SCRIPT tag on the
// page and insert before it.
var runScript = function(url) {
var script = document.createElement('SCRIPT');
script.src = url;
script.type = 'text/javascript';
script.charset = 'UTF-8';
var index = document.getElementsByTagName('SCRIPT')[0];
index.parentNode.insertBefore(script, index);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment