0

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);
}

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah yeah, that did the trick. Is this practice considered viable? I am new at JavaScript so I don't know.
It might be better to use a server-side include, but in lieu of that, this is good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.