作者:飞翔的小鸟52588 | 来源:互联网 | 2024-12-17 17:42
下面是一个改进后的Javascript代码示例,它不仅从服务器获取电影数据并优雅地显示在网页上,还通过注册Service Worker来增强应用的离线功能。
async function displayMovies() {
const respOnse= await fetch('/api/getMovies');
const movieData = await response.json();
const movies = movieData.results.slice(0, 12); // 假设返回的结果字段为results,并取前12条记录
console.log(movies);
let htmlCOntent= '';
movies.forEach(movie => {
htmlContent += `${movie.id} === ${movie.releaseDate}`;
});
document.querySelector('.movie-list').innerHTML = htmlContent;
}
async function activateServiceWorker() {
window.addEventListener('load', async () => {
if ('serviceWorker' in navigator) {
try {
await navigator.serviceWorker.register('/service-worker.js');
console.log('Service Worker 注册成功');
} catch (error) {
console.error('Service Worker 注册失败:', error);
}
} else {
console.warn('当前浏览器不支持 Service Worker');
}
});
}
displayMovies();
activateServiceWorker();
if (Notification.permission === 'default') {
Notification.requestPermission().then(permission => {
if (permission === 'granted') {
console.log('用户同意接收通知');
} else {
console.log('用户拒绝接收通知');
}
});
}
if (!navigator.onLine) {
new Notification('系统提示', { body: '当前无网络连接,正在使用缓存数据' });
}
window.addEventListener('online', () => {
new Notification('系统提示', { body: '已恢复网络连接,请刷新页面获取最新数据' });
});
window.addEventListener('offline', () => {
new Notification('系统提示', { body: '网络已断开,将使用缓存数据' });
});