问题描述
我制作了一个天气网页,它使用 API 来提取数组信息并将其显示在我的网页上。它提取天气数据,例如条件、温度、风速和天气图标图像。该代码运行良好。我的问题是我不应该有任何超过 500kb 的网页,而使用 API 的网页使用了大约 3000。有没有办法减少 kb 的使用?下面是我正在使用的代码。如果我写的不同,会不会导致 kb 使用量下降?
//json source
const apiURL = `https://api.openweathermap.org/data/2.5/forecast?
id=${5604473}&units=imperial&appid=00000000000000000000000000000000`;
fetch(apiURL)
.then((response) => response.json())
.then((jsObject) => {
//console.log(jsObject);
document.getElementById('currently').textContent = jsObject.list[0].weather[0].main;
document.getElementById('high').textContent = jsObject.list[0].main.temp_max;
document.getElementById('windspeed').textContent = jsObject.list[0].wind.speed;
document.getElementById('humidity').textContent = jsObject.list[0].main.humidity + "%";
document.getElementById('windchill').innerHTML = windchill;
//calculate windchill
let t = (jsObject.list[0].main.temp);
let s = (jsObject.list[0].wind.speed);
if (t <= 50 && s >= 3) {
document.getElementById("windchill").innerHTML = windchill(t,s).toFixed(0);
} else {
document.getElementById("windchill").innerHTML = "N/A";
}
function windchill(t,s) {
let w = Math.round(35.74 + 0.6215 * t - 35.75 * Math.pow(s,0.16) + 0.4275 * t *
Math.pow(s,0.16));
return w;
};
});
//forecast
const forecastURL = `https://api.openweathermap.org/data/2.5/forecast?
id=${5604473}&units=imperial&appid=00000000000000000000000000000000`;
fetch(forecastURL)
.then((response) => response.json())
.then((jsObject) => {
const forecastweek = jsObject.list.filter(x => x.dt_txt.includes('18:00:00'));
let day = 0;
const dayofweek = ['Sun','Mon','Tues','Wed','Thur','Fri','Sat'];
forecastweek.forEach((x) => {
let d = new Date(x.dt_txt);
//console.log(d);
document.getElementById(`dayofweek${day + 1}`).textContent = dayofweek[d.getDay()];
const imagesrc = 'https://openweathermap.org/img/wn/' + x.weather[0].icon + '@2x.png';
document.getElementById(`icon${day + 1}`).setAttribute('src',imagesrc);
document.getElementById(`forecast${day + 1}`).innerHTML = (x.main.temp);
day++;
})
});
解决方法
仅通过调用 API 并加载几个图标就不太可能达到 500kB 的限制。给定 API 请求的响应返回 +/- 16kB 的有效负载,每个图标的大小为 +/- 2kB。总共 7 天,我预计最大消耗量为 50kB。
为了进一步调查,我建议您使用浏览器的开发人员工具检查网络流量。对于 Chrome 浏览器,可以找到明确的说明here。
此外,您是否有理由两次执行相同的 API 请求(如示例代码所示)?
,感谢您的链接。我会检查一下。是的,我使用了两次相同的 API 请求,因为我将它用于网页上的两个独立部分
,另外一个想法,检查响应是否有 cookie。 IMO 应该由无 cookie 的域提供服务。