Created
May 31, 2021 15:42
-
-
Save iamrobert/a8907c30a66961340d2dd4cd53493ba9 to your computer and use it in GitHub Desktop.
Vanilla JS | Get CSS & JS Example
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
/* + GET JS | |
----------------------------------------------------------------------- | |
https://stackoverflow.com/questions/16839698/jquery-getscript-alternative-in-native-javascript | |
==========================================================================*/ | |
var getJS = function getJS(url) { | |
return new Promise(function(resolve, reject) { | |
var script = document.createElement("script"); | |
script.src = url; | |
script.async = true; | |
script.onerror = reject; | |
script.onload = script.onreadystatechange = function() { | |
var loadState = this.readyState; | |
if (loadState && loadState !== "loaded" && loadState !== "complete") | |
return; | |
script.onload = script.onreadystatechange = null; | |
resolve(); | |
}; | |
document.head.appendChild(script); | |
}); | |
}; | |
// EXAMPLE | |
var templateUrl = location.origin + '/js/'; | |
getJS(templateUrl + 'test.js') | |
.then(function() { | |
console.log("Loaded") | |
}) | |
.catch(function() { | |
console.error("Could not load script"); | |
}); | |
/* + GET JS | |
----------------------------------------------------------------------- | |
https://getbutterfly.com/how-to-add-a-css-stylesheet-in-vanilla-javascript/ | |
==========================================================================*/ | |
function getCSS(path) { | |
// console.log('Requesting ' + path + '... in progress'); | |
if (document.createStyleSheet) { | |
try { | |
// console.log('Loading ' + path + '... in progress'); | |
document.createStyleSheet(path); | |
} | |
catch (e) { | |
console.error('Failed dynamically loading stylesheet.'); | |
} | |
} | |
else { | |
var css; | |
css = document.createElement('link'); | |
css.rel = 'stylesheet'; | |
// css.type = 'text/css'; | |
css.media = 'all'; | |
css.href = path; | |
document.getElementsByTagName('head')[0].appendChild(css); | |
console.log('Appending ' + path + ' to document head... success'); | |
} | |
} | |
//EXAMPLE | |
getCSS('https://www.example.com/path/to/assets/stylesheet.css'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment