Slow weather app - need some help & feedback

Slow weather app - need some help & feedback
0

#1

Currently on the Intermediate Front End projects and the weather app has been giving me some trouble. I finally got geolocation and the openweather api to fetch the data but it’s incredibly slow to load! I have a hunch my problem might have to do with async but when I set it to true the whole thing breaks. Here is my code:

var weather = new XMLHttpRequest();

var getLocation = function(){

	if(navigator.geolocation){

		navigator.geolocation.getCurrentPosition(function(position){
			var lat = "lat=" + position.coords.latitude;
			var lon = "lon=" + position.coords.longitude;
			var url = "http://api.openweathermap.org/data/2.5/weather?" + lat + "&" + lon + "&units=imperial&appid=fdfc5c8fb2daad3f0a93f1d46a08c3a6";

			weather.open("GET", url, false);
			weather.send(null);

			var data = JSON.parse(weather.responseText);
			var city = data.name;
			var temp = Math.round(data.main.temp) + "°";
			var description = data.weather[0].description;

			function getWeather(id, res){
				document.getElementById(id).innerHTML = res;
			}

			getWeather("displayTemp", temp);
			getWeather("displayCity", city);
			getWeather("displayDescription", description);

		});

	} else {
		window.alert("Could not get location");
	}
}

getLocation();

See it live

Any feedback, resources or nudges in the right direction would be greatly appreciated! I want to understand this project through vanilla js and clean up my code as much as possible before moving on.


#2

One reason the page loads slow (at least the first time), is because of the 3.5 MB rain.jpg image you are displaying. Find a much smaller file size for an image (say max of 250KB).

Also, you need to use https preffix for the OpenWeather API, because you site is https and modern browsers will not block unsecure requests.

Lastly, you should be using true for your weather.open call, to make an asynchronous call instead of a synchronous call. You are correct that you will need to modify your code to check to see when the data comes back successfully. Take a look at how to use XMLHttpRequest for how to approach this.


#3

Thanks for the guidance! I appreciate it!