Question

I recently added a weather forecast to my website. The script is as follows:

After the footer:

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

The 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);
        }

}); });

I noticed that my site takes significantly longer to load.

Is there anything that I can do speed things up? Maybe delay the weather forecast

Was it helpful?

Solution

Try removing async:false.

Ajax is designed to be asynchronous. Putting async:false is a bad idea, and there's always a better way.

Having async:false makes everything, even your GUI update, wait on completion of the task. That's not what you want.

Here's a pretty good article about it: http://javascript.about.com/od/ajax/a/ajaxasyn.htm

OTHER TIPS

"async:true" will allow other scripts to run while your ajax request is being treated. This way your ajax request will not be blocking the page load anymore.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top