Skip to content

Instantly share code, notes, and snippets.

@dbrewitz
Created November 29, 2016 19:34
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 dbrewitz/4a41eaa6ed27f021c083ad5c30442348 to your computer and use it in GitHub Desktop.
Save dbrewitz/4a41eaa6ed27f021c083ad5c30442348 to your computer and use it in GitHub Desktop.
add a script or link element to the head of a html page using javascript
// a script to add a script link or css link to the head of a html page
function addMyLink(element, url, type, rel, id) {
var head = document.getElementsByTagName('head')[0]
var myLink = document.createElement(element)
if (element === 'script') {
myLink.src = url
} else if (element === 'link') {
myLink.href = url
if(rel){myLink.rel = rel}
}
if(type){myLink.type = type}
if (id) {myLink.id = id}
head.appendChild(myLink)
}
// here are examples of usage
// addMyLink('script', 'https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js')
// addMyLink('script', 'https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js', 'text/javascript', '', 'myScripts')
// addMyLink('link', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css')
// addMyLink('link', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css', 'text/css', 'stylesheet', 'myStylesheet')
// addMyLink('link', 'https://developers.google.com/_static/f54730da32/images/favicon.png', 'image/vnd.microsoft.icon', 'shortcut icon', 'favicon')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment