简体   繁体   中英

Javascript innerHTML is loading slowly

I wanted to avoid having to make my menu on 5 different pages every time I wanted to make a change. So I used Javascript to recreate the menu at runtime, so that I can just change that script to make the menu change on all pages at once (I know, genius right?).

But here is the thing; While the code works as intended, the menu seems to first load, when the rest of the page have loaded even though I call the function with window.onload . I don't really know why that is. My guess would be that innerHTML is slow, or I load the script at the wrong time.

I tried loading it at <head> but that didn't make much sense considering the DOM doesn't exist yet. So I moved it down to the header tag, which is where the menu code originally was so that it loads when that header does. But it's the exact same behaviour.

If I enter any of the other pages where the menu is written directly in HTML, it loads right away like the rest of the page. Any suggestions?

window.onload = function () {
    var header = document.getElementById("header");
    var div = document.createElement('div');
    div.className = 'inner';

    div.innerHTML =
        '<h1><a href="-omitted-" id="logo">Dynamic Realities</a></h1>' +
        '<nav id="nav"><ul>' +
        '<li><a href="-omitted-">Home</a></li>' +
        '<li><a href="-omitted-" target="_blank">Forum</a></li><li>' +
        '<a href="-omitted-">Media</a></li>' +
        '<li><a href="-omitted-">The Team</a></li>' +
        '<li><a href="-omitted-">Open Positions</a></li></ul></nav>';
    header.appendChild(div);
}

Right. window.onload is going to fire after the rest of the DOM has been loaded.

If you're placing it in the header, where it belongs in the DOM, you can remove the onload event, and just do it right there. That should make it work better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM