【问题标题】:jQuery - How to prevent Weather API from slowing down my website?jQuery - 如何防止 Weather API 减慢我的网站速度?
【发布时间】:2014-06-03 18:52:04
【问题描述】:

我最近在我的网站上添加了天气预报。脚本如下:

在页脚之后:

<script type="text/javascript" src="../js/weather.js"></script>

jQuery:

jQuery(document).ready(function($) {

$.ajax({
type: 'GET',
url: "http://api.worldweatheronline.com/free/v1/weather.ashx?q=Gstaad&format=json&num_of_days=5&key=key",
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function (response) {
    var weather = response.data.weather;
    var weekdays = ["SUN", "MON", "TUES", "WED", "THU", "FRI", "SAT"];
    var ids = ['#first_', '#second_', '#third_', '#fourth_', '#fifth_'];
    for (var i = 0; i < weather.length; i++) {    

        $(ids[i]+"img").attr('src', "http://swissskiresorts.com/wp-content/themes/swiss-ski-resorts/images/day/"+weather[i].weatherCode+".png");
        $(ids[i]+"img").attr('title', weather[i].weatherDesc[0].value);
        $(ids[i]+"min").text(weather[i].tempMinC);
        $(ids[i]+"max").text(weather[i].tempMaxC);

        if(i > 0)
            {                           
        var d = new Date(weather[i].date);
        $(ids[i]+"day").text(weekdays[d.getDay()]);
            }
            }
                console.dir(response);
            },
            error: function (e) {
                console.log(e.message);
        }

}); });

我注意到我的网站需要更长的时间才能加载。

有什么可以加快速度的吗?可能会延迟天气预报

【问题讨论】:

  • 部分问题在于async: false。通过这样做,您将锁定屏幕。将 async 设置为 false 只是一个非常非常糟糕的主意。总会有更好的方法。
  • 您好,感谢您的提示!我应该将 async 设置为 true 吗?
  • 是的,或者只是删除该属性。默认情况下为真。但是,可以肯定的是,我需要查看循环中的内容。
  • 亲爱的乔纳森,我已经更新了 sn-p。你相信它可以改进吗?我搞砸了什么吗? :-(

标签: jquery weather-api


【解决方案1】:

尝试删除async:false

Ajax 被设计为异步的。输入async:false 是个坏主意,但总会有更好的方法。

拥有async:false 会让一切,甚至是您的 GUI 更新,都在等待任务完成。这不是你想要的。

这是一篇非常好的文章:http://javascript.about.com/od/ajax/a/ajaxasyn.htm

【讨论】:

    【解决方案2】:

    "async:true" 将允许在处理您的 ajax 请求时运行其他脚本。 这样您的 ajax 请求就不会再阻塞页面加载了。

    【讨论】:

      猜你喜欢
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多