javascript - DOM 准备好之前获取 DOM 准备好之后回调

标签 javascript fetch

背景

我正在使用 openweathermap 显示曼彻斯特的当前温度和状况,代码运行良好。

HTML

<div class="wp-block-pbf-block-weather" data-key="*******************" data-city="2643123">
    <p>The Current Weather in <span id="city">Manchester</span> 
        is <span id="temp">probably 13</span>°C 
        with <span id="condition">doom and gloom</span>
    </p>
</div>

Javascript

function weatherBalloon( cityID, APIkey ) {
    fetch('https://api.openweathermap.org/data/2.5/weather?id=' + cityID+ '&appid=' + APIkey)
    .then(function(resp) { if (!resp.ok) {
    throw new Error('Network response was not ok');
    }
    return resp.json() }) // Convert data to json
    .then(function(data) {

        document.getElementById("temp").innerHTML = Math.round(data.main.temp - 273.15);
        document.getElementById("condition").innerHTML = data.weather[0].description;
        console.log(data);

        var cat = "part_cloud"; // set default weather category
        var id = data.weather[0].id;
        if (id >= 200 && id <= 299) { cat = "thunder"};
        if (id >= 300 && id <= 399) { cat = "rain"};
        if (id >= 500 && id <= 531) { cat = "rain"};
        if (id >= 600 && id <= 699) { cat = "snow"};
        if (id >= 700 && id <= 799) { cat = "fog"};
        if (id == 800 ) { cat = "sun"};
        if (id >= 801 && id <= 802) { cat = "part_cloud"};
        if (id >= 803 && id <= 804) { cat = "cloud"};

        var video = window.location.origin + "/wp-content/uploads/bg_video_" + cat + ".mp4";
        console.log(video);
    })
    .catch(error => {
        console.error('There has been a problem with your fetch operation:', error);
        console.log ("OH NO Something Has Gone Wrong!")
    });
}



(function($){
    $(document).ready( function(){
        var cityID = $('.wp-block-pbf-block-weather').data('city');
        var APIkey = $('.wp-block-pbf-block-weather').data('key');
        weatherBalloon( cityID, APIkey );

    });



})(jQuery);

问题

因为我在 dom 准备好后调用 Wea​​therBalloon 函数,所以 JS 使用从 api 接收到的值更新默认 html 时存在明显的延迟。

需要帮助

如何在 dom 准备好之前调用 fetch 并在 dom 准备好之后让回调更新 html,以便有望消除/减少更新 html 时的可见延迟? 我尝试过使用异步和等待,但无法让任何东西工作 干杯!

最佳答案

您可以在任何您喜欢的地方等待 promise 。您还可以在任何您喜欢的地方添加事件监听器,但是您必须处理事件已经发生的情况,尤其是在 DOM 准备就绪时。这是后一个选项的工作示例:

<html>
<body>

<script>
// more about docReady: https://stackoverflow.com/questions/9899372/
function docReady(fn) {
  if (document.readyState === "complete" || document.readyState === "interactive") {
    console.log('document already ready');
    setTimeout(fn, 1);
  } else {
    console.log('adding event listener');
    document.addEventListener("DOMContentLoaded", fn);
  }
}

// the function to be called on "DOM ready"
function showData(data) {
  const output = document.getElementById('output');
  output.innerHTML = JSON.stringify(data);
}

// self executing function (async/await style)
!async function() {
  const response  = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  const data = await response.json();

  console.log(data);
  docReady(showData(data));
}();
</script>

<div id="output"></div>

</body>
</html>

关于javascript - DOM 准备好之前获取 DOM 准备好之后回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64222907/

相关文章:

javascript - 我可以使用Safari移动用户代理自动执行Apple Pay吗

javascript - 自定义编码字符串

javascript - 交叉抓取和同构抓取有什么区别?

ios - NSPredicate 用于多天全天事件

javascript - 模拟 Tableau 的嵌入式悬停工具图

JavaScript 数据结构

javascript - 在哪里可以获得将法定货币金额转换为加密货币值(value)的加密 API

javascript - $.when 使用多个 fetch() 会破坏 Backbone 模型

c - ARM - 使用 16 位数据总线获取 32 位数据

php - while 循环只找到最后一次迭代