javascript - DOM 完成后运行脚本

标签 javascript html

我正在根据外部文件的标题动态创建要放置在菜单栏上的菜单项,并使用 XMLHttpRequest() 导入。 。当我浏览不同的页面时,此菜单栏会动态更新。

这很好用。 我将每个文档加载到单独的 div 中元素,在一堆卡片中,并隐藏除 setVisible() 之外的所有元素页。

 window.onload = function(){
     loadContent("personalinfo");
     loadContent("academicalinfo");
     loadContent("employmentinfo");
     setVisible("academicalinfo");
     /*setMenues("academicalinfo");*/
}

setVisible()的最后一个 Action 就是调用setMenues() ,它负责读取所述主窗口的所有标题。这也可以正常工作。

function loadMenues(file) {
     var rightmenu = document.getElementById("right-menu");
     while(rightmenu.firstChild){
         rightmenu.removeChild(rightmenu.firstChild);
     }
     [].forEach.call(document.getElementById(file).children,
         function(custompaddingchild) {
             /* searching for h1 and adding menu items happens here */
         }
     );

当 DOM 元素尚未加载时(如页面加载时),就会出现问题。由于在页面完全呈现之前,文档元素中没有 ElementsById(file),因此无法在加载时添加菜单项。

我尝试在窗口的“load”事件和文档上添加一个EventListener,我尝试在主页正文的末尾以及onload=上执行该函数。 <body> 的参数(它甚至在捕获子页面之前运行,给我留下一个空白页面而不是实际内容),但看起来,在页面完全加载后,它们似乎都没有发生。

在运行函数之前添加 2 秒的延迟并不是一个有效的解决方案。另外,在onload函数中添加延迟不会影响结果,只会增加加载时间两秒。

单击任何更新菜单的菜单都会按预期工作。唯一的问题是加载。

<div class="menu-item" onclick="setVisible('personalinfo');"><span>Personal information</span></div>

如何确保页面将 setVisible() 函数延迟到页面呈现之后? 我发现的所有来源都声称“load”事件在页面呈现后触发,但在我的情况下似乎没有被触发。 DOMContentLoaded事件也没有被触发,但我怀疑我不想要这个。 click事件,或 scroll相反,窗口上的事件会正确触发。

Mozilla, Window: load event

Javascript.info, Page: DOMContentLoaded, load, beforeunload, unload

编辑:根据请求,这里是loadContent():

function loadContent(file) {
        var request = new XMLHttpRequest();
        request.open("GET", file+".html?_=" + new Date().getTime());
        request.onreadystatechange=function(){
                var loadedcontent = request.responseText;
                document.getElementById(file).innerHTML = loadedcontent;
        }
        request.send();
}

编辑2:

完整代码可在https://github.com/mazunki/portfolioweb-stackoverflowquestion获取

最佳答案

您需要使用 promise :https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

试试这个

function loadContent(file) {
    return new Promise(function (resolve, reject) {
        var request = new XMLHttpRequest();
        request.open("GET", file+".html?_=" + new Date().getTime());
        request.onreadystatechange=function(){
            var loadedcontent = request.responseText;
            document.getElementById(file).innerHTML = loadedcontent;

            resolve();
        }
        request.send();
    });
}

window.onload = function(){
    // when you finish all the content loading
    Promise.all([
        loadContent("personalinfo"),
        loadContent("academicalinfo"),
        loadContent("employmentinfo")
    ]).then(function() {
        // Load menu
        setVisible("academicalinfo");
        /*setMenues("academicalinfo");*/
    })
}

关于javascript - DOM 完成后运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55716806/

相关文章:

javascript - 如何使用JQuery读取href属性

javascript - 使用 JavaScript 重新加载页面时出现问题

html - 如何在 excel WebBrowser 控件上调整图像大小

html - 图例标签和 Chrome

javascript - 慢速 Canvas 元素

javascript - 如何根据目录结构和文件创建嵌套对象

javascript - 缩小的嘶嘶声

html - 使用 Bootstrap 的响应式布局

javascript - jQuery animate 在 Firefox 中实现 div 跳跃

javascript - 切换多个 Div 并在点击时停用