skip to Main Content

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


  1. <script src="fileName.js"></script>

    Login or Signup to reply.
  2. 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).

    var responseText = this.responseText || `
    <h1>html section</h1>
    <scr` + `ipt>
    console.log("js section")
    </scr` + `ipt>
    `;
    
    var arr = responseText.split("<scr" + "ipt>")
    var html = arr[0];
    div.innerHTML = html;
    if (arr.length > 1) {
      var src = arr[1].split("</scr" + "ipt>")[0];
    
      // add script tag
      var script = document.createElement("script");
      script.textContent = src;
      document.head.appendChild(script);
    }
    <div id="div"></div>
    Login or Signup to reply.
  3. 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 :

    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;
            /* Loop For The Scripts Inside The pageCont DIV */
            for (script of document.getElementById('pageContent').querySelectorAll('script')) {
                var scriptElem = document.createElement('script');
                if (script.src !== '' && typeof script.src !== 'undefined') {
                    scriptElem.src = script.src;
                } else {
                    scriptElem.innerHTML = script.innerHTML;
                }
                document.head.appendChild(scriptElem);
            }
        };
        xhr.send();
    }
    

    This even supports external scripts (i.e. scripts with src attribute set to another JavaScript file)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search