使用不同的 Lottie 动画而不发出 http 请求

问题描述

我正在开发一个与骰子相关的小游戏。我有 6 个 Lottie 动画,每个动画都是一个死脸。 当用户单击“滚动”时,随机骰子面朝上。因此是随机的 Lottie 动画。 问题是每个动画文件(json 文件)是 320 kb。每当用户点击滚动时,网站就会发出一个可能需要 300-400 毫秒的 http 请求。 我正在寻找一种无需 http 请求即可使用这些动画的方法。换句话说,每当我点击滚动动画呈现流畅。此外,我更喜欢该解决方案对未来计划友好。

the game I'm creating

解决方法

您可以在页面加载时执行请求,并将结果存储在 LocalStorage 中,以供您在需要时使用。

localStorage.setItem('dice-face-1',JSON.stringify(LottieContent));
const diceFace1 = JSON.parse(localStorage.getItem('dice-face-1'));
localStorage.setItem('dice-face-2',...

LocalStorage documentation on MDN

进一步说明:这也会为下次访问您的游戏的用户存储骰子面“彩票数据”:)

然后您还需要能够使缓存的数据无效,因此当您更新您的彩票数据时,用户也会获得您想要的数据。

const newVersion = 1.03;
localStorage.setItem('lottie-data-version',1.02);
const lottieDataVersion = localStorage.getItem('lottie-data-version');
if(lottieDataVersion < newVersion){
  localStorage.removeItem('dice-face-1');
  ...(invalidate other data)
}