I have a problem with using js scripts inside HTML files. There are 2 HTML files a and b. b is included inside a by using the script below.
function includeHTML() {
var z, i, elmnt, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
file = elmnt.getAttribute("w3-include-html");
if (file) {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/* Exit the function: */
return;
}
}
}
I took it from w3school.com, using for include HTML, and my HTML file a and b is shown below:
a.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div w3-include-html="b.html"></div>
<script>
includeHTML();
</script>
</body>
</html>
And the b.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h4>The gist enbed link:</h3>
<script src="https://gist.github.com/meminb/8e2488a47bacc7e93e645022d3dc3af1.js"></script>
</body>
</html>
I am expecting to be able to see the gist that I have embedded with script tags in the a.html file but it does not work. Is there any point I am missing to achieve this, or any other solution to be able to run script tags in included files?
Try this
function includeHTML() {
var z, i, elmnt, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
file = elmnt.getAttribute("w3-include-html");
if (file) {
var iframe = document.createElement('iframe');
iframe.style.cssText = 'border:none;width:100%;height:100%;';
iframe.src = file;
elmnt.removeAttribute("w3-include-html");
elmnt.appendChild(iframe);
setTimeout((f, e) => {
var body = f.contentWindow.document.body;
var html = f.contentWindow.document.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
// console.log(e);
e.style.height = height + 'px';
// console.log(height);
}, 500, iframe, elmnt);
return;
}
}
}