skip to Main Content

I’m having problems getting the JS code linked in the innerHTML of my main HTML page working. I have a main HTML file that has these divs:

<div class="content">
    <div class="intro">
        <img src="nightTree.jpg">
        <div class="inner-intro">
            <h1>EDUPLANNER</h1>
            <p>a student scheduling webapp</p>
        </div>
    </div>
</div>
<div class="scripts">
    <script src="home.js"></script>
</div>

and this is the JS code (home.js) for the main HTML file to insert the innerHTML:

document.addEventListener("DOMContentLoaded", () => {
    const content = document.querySelector(".content"),
    sidebarLinks = document.querySelectorAll(".sidebar a");
 
    sidebarLinks.forEach(link => {
        link.addEventListener("click", event => {
            if (link.classList.contains("do-nothing")) {
                event.preventDefault();
                return;
            }

            event.preventDefault();
            var href = link.getAttribute("href");

            fetch("http://127.0.0.1:5500/" + href)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! Status: ${response.status}`);
                    }
                    return response.text();
                })
                .then(data => {
                    var parser = new DOMParser();
                    var parsedDocument = parser.parseFromString(data, "text/html");
                    
                    if (parsedDocument.querySelector(".day")) {
                        var script = document.createElement("script");
                        script.src = "calendar.js";
                        document.querySelector(".scripts").appendChild(script);
                    }

                    content.innerHTML = parsedDocument.body.innerHTML;
                })
                .catch(error => {
                    console.error("Error fetching content:", error);
                });
        });
    });
});

This is the CSS for "content" class.

.content {
    position: relative;
    background-color: rgb(33, 33, 33);
    height: 100vh;
    width: calc(100% - 80px);
    left: 80px;
    transition: all 0.5s ease;
    padding: 1rem;
}

This is the innerHTML of what I’m trying to get into the main file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Test Page</title>
</head>
<body>
    <div class="day"></div>
    <script src="calendar.js"></script>
</body>
</html>

and the JS code for the innerHTML:

console.log("Test 1");

document.addEventListener('DOMContentLoaded', () => {
    console.log('DOMContentLoaded event fired');

    let dayDiv = document.querySelector(".day");

    // Simplified for testing
    var newDiv = document.createElement("div");
    newDiv.textContent = "Test";
    dayDiv.appendChild(newDiv);

    console.log("For loop executed");
});

console.log("Test 2");

When the innerHTML is loaded on the main page, only "Test 1" and "Test 2" were shown on the console. Everything in document.addEventListener() doesn’t load. I’ve tried changing the fetch codes, where the JS files are parsed and tried window.onload but nothing worked.

P.S. I’m quite new to HTML, CSS and JS so some of my code may be wrong.

2

Answers


  1. It seems like the issue might be related to the way you’re handling the dynamic loading of content and scripts. When you fetch the content and insert it into the main HTML document, the scripts in the fetched content may not be executing as expected.

    Here are a few suggestions to troubleshoot and improve your code:

    1. Execute the Script Manually:
      Instead of directly appending the script element to the document, you can create a new script element, set its content to the script code, and then append it to the document head. This can be done using the innerHTML property.

      if (parsedDocument.querySelector(".day")) {
          var script = document.createElement("script");
          script.innerHTML = data; // Set the script content
          document.head.appendChild(script);
      }
      
    2. Use the insertAdjacentHTML Method:
      Instead of setting content.innerHTML, you can use the insertAdjacentHTML method to insert the content at a specified position. This may help in ensuring that the script is executed.

      content.insertAdjacentHTML('beforeend', parsedDocument.body.innerHTML);
      
    3. Separate Loading and Execution:
      Ensure that the script is loaded and executed separately. You can load the script using the fetch API and then execute it using the Function constructor.

      fetch("calendar.js")
          .then(response => response.text())
          .then(scriptCode => {
              const script = new Function(scriptCode);
              script();
          })
          .catch(error => console.error("Error fetching script:", error));
      
    Login or Signup to reply.
  2. You can’t add JS like you add HTML elements.

    To add JS you need to do it like this…

    var S=document.createElement('script'); 
    
    S.type='text/javascript';
    
    S.src='https://somelibrary.js';  // <--- Use this for a JS file or...
    
    S.text='function Something(){}';  // <--- Use this for direct JS text
    
    document.head.appendChild(S);
    

    Btw, you should replace all instances of…

    document.addEventListener('DOMContentLoaded', () => {
    

    with…

    window.addEventListener('load', () => {
    

    DOMContentLoaded is too premature to be suitable for your needs, unless taking loading measurements which you’re not.

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