This is my first question on SO, so please be patient with me.
I am creating a very small web page that has ‘n basic HTML structure.
<!DOCTYPE html>
<html lang="en">
<head>
<title>BootVid</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" type="image/png" href="img/favicon.png" />
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://vjs.zencdn.net/8.3.0/video-js.css" rel="stylesheet" />
<script src="https://vjs.zencdn.net/8.3.0/video.min.js"></script>
<style>
.fakeimg {
height: 200px;
background: #aaa;
}
</style>
</head>
<body>
<div class="container mt-5">
<div id="pageContent">
<!--Page Content Goes Here-->
</div>
</div>
<script>
document.addEventListener("DOMContentLoaded", () => {
routeTo("videoplayer");
});
function routeTo(path) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'components/' + path + '.html', true);
xhr.onreadystatechange = function () {
if (this.readyState !== 4) return;
if (this.status !== 200) return; // or whatever error handling you want
document.getElementById('pageContent').innerHTML = this.responseText;
};
xhr.send();
}
</script>
</body>
</html>
So this is basically an empty web site with a PAGE CONTENT div that I load HTML code from a seperate .html file into the pageContent div on the "main" page.
The basic routing works 100%. But when I load external html from one of the .html files, the HTML displays fine but the javascript code is never executed. How do I inject html code into a div along with javascript code that needs to execute on load?
Here is an example of a page I need to load in the pageContent div, that initializes a VideoJS instance.
<!--videoplayer.html-->
<div class="container mt-5" id="vidPlayer" hidden>
<div class="mx-auto col-12 col-md-10 col-lg-8">
<video id="my-video" class="video-js vjs-fluid vjs-default-skin" controls preload="none">
<source id="video-source" src=".mp4" type="video/mp4"> <!--video/mp4 application/x-mpegURL-->
</video>
</div>
</div>
<script>
var player = videojs('my-video', {
repsonsive: true,
inactivityTimeout: 2000
});
</script>
Any help would be greatly appreciated.
3
Answers
<script src="fileName.js"></script>
It’s not possible to load a script like this. However, as suggested in comments, through string manipulation you can extract the script part and load it separately.
Let’s assume your
<script>...</script>
is always the last thing on the page (for simplicity).You need to get the script elements from the pageContent div, clone them and append them to document.head. You just only have to change your
routeTo
function.Your
routeTo
function will become like this :This even supports external scripts (i.e. scripts with src attribute set to another JavaScript file)