I have a use case where a html page needs to load the contents of an external html file. The external html file contains html elements and Javascript code.
I want to make use of both html and the Javascript.
I can load and render the html contents, but how do I execute the Javascript in the external file? In this example I want to call staticLoaded
Note - I do not want to use any frameworks, ideally looking to achieve this in native js.
HTML file:
<html>
<body>
<div id="content-here"></div>
<script>
function main(){
fetch('/file-location/')
.then(function (response) {
return response.text();
})
.then(function (html) {
const contentHereDiv = document.getElementById("content-here");
contentHereDiv.innerHTML = html;
});
}
main();
</script>
</body>
</html>
External file:
<html>
<body>
<div>Hello world</div>
<script>
function staticLoaded(){
console.log('Hello world');
}
</script>
</body>
</html>
<html>
<body>
<div id="content-here">
</div>
<script>
function main() {
fetch('/example-page.html')
.then(function(response) {
return response.text();
})
.then(function(html) {
const contentHereDiv = document.getElementById("content-here");
contentHereDiv.innerHTML = html;
}).catch(function(err) {
console.warn('Something went wrong.', err);
});
}
main();
</script>
</body>
</html>
Following suggestions. I came to the following solution.
<html>
<body>
<div id="content-here">
</div>
<script>
function main(){
fetch('/example.html')
.then(function (response) {
console.log('respond');
return response.text();
})
.then(function (html) {
const contentHereDiv = document.getElementById("content-here");
contentHereDiv.innerHTML = html;
console.log('render content');
})
.then(() => {
const staticScript = document.getElementById("static-js").innerHTML;
const scriptElement = document.createElement('script');
scriptElement.setAttribute('type', 'text/javascript');
scriptElement.innerText = staticScript;
const head = document.getElementsByTagName('head')[0];
head.appendChild(scriptElement);
console.log('move script to head');
})
.then(() => {
console.log('call function');
staticLoaded();
})
.catch(function (err) {
console.warn('Something went wrong.', err);
console.log(err.message);
});
}
main();
</script>
</body>
</html>