簡體   English   中英

DOM 准備好前獲取 DOM 准備好后回調

[英]Fetch before DOM is ready Callback after DOM is ready

背景

我正在使用 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 准備好之后調用 weatherBalloon 函數,所以 JS 使用從 api 接收到的值更新默認 html 會出現明顯的延遲。

需要幫助

如何在 dom 准備好之前調用 fetch 並在 dom 准備好后讓回調更新 html,以便希望刪除/減少更新 html 的可見延遲? 我試過玩 async 和 await 但什么也做不了干杯!

你可以在任何你喜歡的地方等待承諾。 你也可以在任何你喜歡的地方添加一個事件偵聽器,但你必須處理事件已經發生的情況,尤其是當涉及到 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM