Last active
March 2, 2023 19:08
-
-
Save ChobPT/58fb052214dc734f8375a346764901e4 to your computer and use it in GitHub Desktop.
Find SSI (ServerSide Includes) and load their HTML
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Finds all HTML comments with the `#include` tag, extracts the file path from the tag, | |
* loads the contents of the file using an XMLHttpRequest, and inserts the file contents into the | |
* DOM, next to the comment node. If the file contents contain any script tags, those scripts are | |
* also added to the DOM and executed. | |
* | |
* Author: chob.pt | |
* | |
*/ | |
function onDocumentReady() { | |
var regex = /<!--#include\s*(.*?)\s*-->/g; | |
var comments = document.documentElement.innerHTML.match(regex); | |
for (var i = 0; i < comments.length; i++) { | |
var content = comments[i].replace(/<!--#include file=\"\s*/, '').replace(/\s*-->/, '').slice(0,-1); | |
rawContent=comments[i]; | |
var xhttp = new XMLHttpRequest(); | |
xhttp.onreadystatechange = function() { | |
if (this.readyState == 4 && this.status == 200) { | |
var outputHTML = this.responseText; | |
var walker = document.createTreeWalker(document, NodeFilter.SHOW_COMMENT, null, false); | |
while (walker.nextNode()) { | |
if ("<!--"+walker.currentNode.nodeValue+"-->" === rawContent) { | |
var newElement = document.createElement('p'); | |
newElement.innerHTML = outputHTML; | |
var newScripts = newElement.querySelectorAll('script'); | |
for (var j = 0; j < newScripts.length; j++) { | |
newScript = document.createElement("script"); | |
newScript.textContent = newScripts[j].textContent; | |
document.body.appendChild(newScript); | |
} | |
walker.currentNode.parentNode.insertBefore(newElement, walker.currentNode); | |
} | |
} | |
} | |
}; | |
xhttp.open("GET", content, true); | |
xhttp.send(); | |
} | |
} | |
document.addEventListener('DOMContentLoaded', onDocumentReady); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment