Skip to content

Instantly share code, notes, and snippets.

@pivanov
Created January 22, 2020 12:13
Show Gist options
  • Save pivanov/bf6a00a381a431df17affeb66ea52c65 to your computer and use it in GitHub Desktop.
Save pivanov/bf6a00a381a431df17affeb66ea52c65 to your computer and use it in GitHub Desktop.
injectInHead example
<!doctype html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function injectInHead({
targetId = "corllete",
src,
type,
loadTimeout = 0,
callbackTimeout = 0,
}, callback) {
var url = src.replace(/^https?:\/\//, "");
var hash = "owned-by-corllete";
var targetEl = document.getElementById(targetId);
if (targetEl) {
targetEl.innerHTML = "";
targetEl.style.cssText = targetEl.style.cssText +
`display: flex;align-items: center;justify-content: center;width: 200px;height: 200px;background: ${targetEl.style.backgroundColor} url(https://thumbs.gfycat.com/UnderstatedFrayedAlabamamapturtle-size_restricted.gif) no-repeat 50% 50% / 100%;`
}
var alreadyExist = document.getElementById(hash);
if (alreadyExist) {
if (callback) {
callback();
}
return null;
}
var f;
if (type === "js") {
f = document.createElement("script");
f.setAttribute("type", "text/javascript");
f.setAttribute("src", `//${url}`);
f.setAttribute("id", hash);
f.setAttribute("defer", true);
}
if (type === "css") {
f = document.createElement("link");
f.setAttribute("id", hash);
f.setAttribute("rel", "stylesheet");
f.setAttribute("type", "text/css");
f.setAttribute("href", `//${url}`);
f.setAttribute("defer", true);
}
if (typeof f !== "undefined") {
var loaded;
setTimeout(() => {
document.getElementsByTagName("head")[0].appendChild(f);
}, loadTimeout);
if (callback) {
f.onload = () => {
if (!loaded) {
setTimeout(() => {
callback();
}, callbackTimeout);
return null;
}
loaded = true;
};
}
}
};
</script>
</head>
<body>
<div id="corllete" style="background: red">placeholder</div>
<script type="text/javascript">
setInterval(() => {
injectInHead({
src: "//cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js",
type: "js",
loadTimeout: 3000,
targetId: "corllete",
}, function () {
var today = moment().format('YYYY-MM-DD');
var html = `<p>today is ${today}</p>`;
var el = document.getElementById("corllete");
el.style.background = 'none';
el.innerHTML = html;
});
}, 3000);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment