Skip to content

Instantly share code, notes, and snippets.

@mikeclagg
Created March 16, 2022 17:18
Show Gist options
  • Save mikeclagg/55c831aeb76dfd997e6a14e8c9e430f2 to your computer and use it in GitHub Desktop.
Save mikeclagg/55c831aeb76dfd997e6a14e8c9e430f2 to your computer and use it in GitHub Desktop.
Vanilla Javascript to swap urls for Styles and Scripts
// local vs remote hostred url (needed for static storage usually)
const prefix = isLocal() ? '.' : 'http://example.com';
// Stylesheet path
const cssPath = '/assets/styles/css/app.css';
// Script path
const scriptPath = '/assets/scripts/js/app.js';
// HTML tag attributes
const cnfgs = [
{ link: { rel: 'stylesheet', type: 'text/css', href: prefix + cssPath } },
{ script: { src: prefix + scriptPath } }
];
// loop to add the above configuration to the document head
cnfgs.forEach((cnfg) => {
const [ type ] = Object.keys(cnfg);
const el = document.createElement(type);
Object.assign(el, cnfg[ type ]);
document.head.appendChild(el);
});
function isLocal() { return /localhost/.test(location.hostname); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment