Skip to content

Instantly share code, notes, and snippets.

@juliandescottes
Last active April 26, 2024 23:03
Show Gist options
  • Save juliandescottes/6201227 to your computer and use it in GitHub Desktop.
Save juliandescottes/6201227 to your computer and use it in GitHub Desktop.
HTML partials purely client side. 4 lines of javascript + iframes. Works on Chrome, Firefox, IE7 to IE10. That's probably not new, but I find it pretty cool for small/medium projects.
// SUPER CHEAP TEMPLATES !
window.loadCheapPartial = function (event) {
var iframe=event.target || event.srcElement, div=document.createElement("div");
// using contentWindow.document instead of contentDocument for ie6/7 compatibility
div.innerHTML = iframe.contentWindow.document.body.innerHTML;
if (div.children.length == 1) div = div.children[0];
iframe.parentNode.replaceChild(div, iframe);
};
<!doctype html>
<html>
<head>
<title>Cheap partials demo</title>
</head>
<body>
<script type="text/javascript" src="cheap-partials.js"></script>
<iframe src="my-partial.html" onload="loadCheapPartial(event)"></iframe>
<iframe src="my-other-partial.html" onload="loadCheapPartial(event)"></iframe>
</body>
</html>
<span>Yay, I can split my html code without having a big JS framework</span>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment