简体   繁体   English

JavaScript innerHTML加载缓慢

[英]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. 我想避免每次想要进行更改时都必须在5个不同的页面上进行菜单设置。 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?). 因此,我使用Javascript在运行时重新创建菜单,这样我就可以更改该脚本以一次在所有页面上更改菜单(我知道,天才吧?)。

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 . 尽管代码按预期工作,但即使我使用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. 我的猜测是innerHTML速度慢,或者我在错误的时间加载了脚本。

I tried loading it at <head> but that didn't make much sense considering the DOM doesn't exist yet. 我尝试在<head>加载它,但是考虑到DOM还不存在,这没有多大意义。 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. 因此,我将其向下移动到header标签,该标签最初是菜单代码所在的位置,以便在该header代码加载时加载。 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. 如果我输入菜单直接以HTML编写的其他页面,则它将立即加载该页面的其余部分。 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. DOM的其余部分加载完毕后window.onload将被触发。

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. 如果将其放置在DOM所属的标头中,则可以删除onload事件,然后就在此处进行。 That should make it work better. 那应该使它更好地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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