可以通过使用 localStorage 或 sessionStorage 实现磁盘缓存来避免相同的 SVG 图标重复请求。以下是一个使用 localStorage 的示例:
function fetchIcon(iconName) {
var iconUrl = '/icons/' + iconName + '.svg';
// Check if icon exists in localStorage
if (localStorage.getItem(iconUrl)) {
// If it does, return the cached icon
return localStorage.getItem(iconUrl);
}
// If it does not exist in localStorage, fetch the icon and store it
// in localStorage before returning it
return fetch(iconUrl)
.then(response => response.text())
.then(svg => {
localStorage.setItem(iconUrl, svg);
return svg;
});
}
在上面的代码示例中,如果图标已经存在于 localStorage 中,则直接返回缓存的图标。否则,使用 fetch() 方法请求图标并将其存储在 localStorage 中,然后返回响应。
使用 sessionStorage 的实现方式类似,只需将 localStorage 替换为 sessionStorage 即可。
这种方法可以大大减少网络请求次数,提高页面加载速度。
上一篇:避免向数组中添加空值