Skip to content

Instantly share code, notes, and snippets.

@anova
Created April 3, 2020 08:00
Show Gist options
  • Save anova/90229dad97e930e111874616af96225a to your computer and use it in GitHub Desktop.
Save anova/90229dad97e930e111874616af96225a to your computer and use it in GitHub Desktop.
Add some additional css and html on runtime. (I am using this method for landing pages)
(function () {
const base_path = 'https://example.com/base/path/';
function addStyle(name) {
const path = base_path + 'css/' + name + '?v=' + Date.now();
const link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = path;
document.head.appendChild(link);
}
addStyle('stylesheet.css');
function addHtml(filename, target_selector) {
const path = base_path + 'html/' + filename + '?v=' + Date.now();
const target = document.querySelector(target_selector);
console.log('target (' + target_selector + ')', target);
if (!target) {
return;
}
const xhr = new XMLHttpRequest();
xhr.open('GET', path);
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
target.innerHTML = xhr.responseText;
}
};
xhr.send();
}
addHtml('source.html', '.target-element-on-page');
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment