Skip to content

Instantly share code, notes, and snippets.

@OlegChuev
Last active January 28, 2025 11:27
Show Gist options
  • Save OlegChuev/82e65737129e4efb72b661e7ef64c9fb to your computer and use it in GitHub Desktop.
Save OlegChuev/82e65737129e4efb72b661e7ef64c9fb to your computer and use it in GitHub Desktop.
Rive JS Runtime Assets Caching
// helpers/rive.js
/**
* Fetches and caches Rive animation data using localStorage
* @param {string} url - The URL of the Rive animation file
* @returns {Promise<ArrayBuffer>} The animation data as ArrayBuffer
*/
export async function getAnimationData (url) {
const cacheKey = `rive-animation-${url}`
// Try to get from localStorage first
const cached = localStorage.getItem(cacheKey)
if (cached) {
return Uint8Array.from(atob(cached), c => c.charCodeAt(0)).buffer
}
// Fetch and cache
const buffer = await fetch(url).then(r => r.arrayBuffer())
try {
localStorage.setItem(cacheKey, btoa(String.fromCharCode(...new Uint8Array(buffer))))
} catch {
clearOldAnimations()
}
return buffer
}
/**
* Removes all cached Rive animations from localStorage
* Used when storage quota is exceeded
*/
function clearOldAnimations () {
Object.keys(localStorage)
.filter(key => key.startsWith('rive-animation-'))
.forEach(key => localStorage.removeItem(key))
}
//
//
// Place where you render your animation
//
//
import { Rive } from '@rive-app/canvas'
import { getAnimationData } from '../helpers/rive'
const animationData = await getAnimationData(this.urlValue)
new Rive({
buffer: buffer,
// Other fields
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment