马上注册,免费下载更多dz插件网资源。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
今天给大家分享一个干货:使用serviceWorker来优化web前端,大大提高google的评分
直接上代码吧:网页中加入
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
console.log('SW registration succeeded with scope:', registration.scope);
}).catch(function(e) {
console.log('SW registration failed with error:', e);
});
}
</script>
sw.js文件
const CACHE_NAME = 'lcget-com-cache';
//安装
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache =>
cache.addAll([
'https://www.lcget.com/public3/lcget/js/fl.js',
'https://www.lcget.com/public3/lcget/js/jquery.lazyload.min.js',
'https://www.lcget.com/public3/lcget/js/alert.js',
'https://www.lcget.com/public3/lcget/js/jquery-3.1.0.min.js',
'https://www.lcget.com/public3/lcget/js/all.css',
'https://www.lcget.com/public3/lcget/pc/app.css',
'https://www.lcget.com/public3/lcget/wap/app.css',
'https://www.lcget.com/public3/lcget/js/grey.gif',
'https://www.lcget.com/public3/lcget/xfdiv.png',
'https://www.lcget.com/public3/noads.jpg',
'https://www.lcget.com/public3/lcget/js/t.js',
'https://www.lcget.com/public3/lcget/js/i.js',
'https://www.lcget.com/public3/lcget/PhotoSwipe/my-gallery.js',
'https://www.lcget.com/public3/lcget/PhotoSwipe/js/photoswipe-ui-default.min.js',
'https://www.lcget.com/public3/lcget/PhotoSwipe/js/photoswipe.min.js',
'https://www.lcget.com/public3/lcget/fonts/fontawesome-webfont.woff2'])
)
);
});
//获取
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(response => {
if (response) {
//found cached resource
return response;
}
// get resource and add it to cache
return fetch(event.request)
.then(response => {
// check if the response is valid
if (!response.ok) {
return response;
}
if(event.request.method=='GET'){
const newResponse = response.clone();
caches.open(CACHE_NAME).then(cache =>cache.put(event.request, newResponse)
);
}
return response;
});
})
);
});
//更新
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(keys => {
return Promise.all(
keys.map(cache => {
if (cache === CACHE_NAME) {
return caches.delete(cache);
}
})
);
})
);
});
效果,LCP,减少一半,是不是很爽
©DZ插件网所发布的一切资源仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。 网站部分内容来源于网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,得到更好的正版服务。 您在本站任何的赞助购买、下载、查阅、回复等行为等均表示接受并同意签订《DZ插件网免责声明协议》。 如有侵权请邮件与我们联系处理: discuzaddons@vip.qq.com 并出示相关证明以便删除。敬请谅解!
|
|