Created
November 29, 2016 19:34
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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