You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让HTML页面footer等待async await接口请求完成后再渲染显示

实现逻辑说明

HTML会从上到下同步解析渲染DOM节点,异步接口请求不会阻塞页面初始渲染,因此写在<main>标签后的footer会在页面加载完成后直接显示,和你写的async/await异步拉取逻辑不冲突,只需要手动控制footer的显隐时机即可。

具体修改步骤

  1. 先给footer添加默认隐藏的样式,避免页面初始化时提前显示
    先在CSS中添加隐藏类:

    .hidden {
      display: none;
    }
    /* 如果想要避免显隐时的布局跳动,可以用透明度方案:
    footer {
      visibility: hidden;
      opacity: 0;
      transition: opacity 0.2s ease;
    }
    footer.show {
      visibility: visible;
      opacity: 1;
    }
    */
    

    对应修改HTML的footer结构,添加默认隐藏类:

    <footer class="hidden">
      <p class="footer-paragraph">
        Made with &#10084;&#65039; in <span class="year">2021</span> by Mahmoud
        Abdulmuty
      </p>
    </footer>
    
  2. 修改JS逻辑,在接口请求完成后(无论成功失败)显示footer
    给createArticle函数添加异常捕获和finally逻辑,保证任何情况下请求结束后footer都会正常展示:

    async function createArticle(
      category = "",
      apiLink = "https://newsapi.org/v2/top-headlines?country=eg"
    ) {
      const apiKey = "&apiKey=3bd4753c68144c04b3eb73e44b7da657";
      const mainEl = document.querySelector(".main");
      const footerEl = document.querySelector("footer");
      mainEl.textContent = "";
    
      try {
        const response = await fetch(apiLink + category + apiKey);
        const responseText = await response.json();
    
        const articles = responseText.articles;
        if (articles.length === 0) {
          mainEl.innerHTML = "No data Found";
        } else {
          displayArticles(articles);
        }
      } catch (error) {
        // 接口请求报错时给用户提示
        mainEl.innerHTML = "新闻加载失败,请刷新页面重试";
        console.error("请求错误:", error);
      } finally {
        // 无论请求成功/失败,都执行显示footer的逻辑
        footerEl.classList.remove("hidden");
        // 如果用的是透明度方案,就换成添加show类:
        // footerEl.classList.add("show");
      }
    }
    

内容的提问来源于stack exchange,提问作者Mahmoud Abdulmuty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 20:45:02