Skip to content

Instantly share code, notes, and snippets.

@iamrobert
Created May 31, 2021 15:42
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 iamrobert/a8907c30a66961340d2dd4cd53493ba9 to your computer and use it in GitHub Desktop.
Save iamrobert/a8907c30a66961340d2dd4cd53493ba9 to your computer and use it in GitHub Desktop.
Vanilla JS | Get CSS & JS Example
/* + 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