serviceWorker提升web前端打开速度,秒开网页提高谷歌优化评分

使用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',
'//www.qingtianseo.com/usr/uploads/auto_save_image/bbd3310c30d81ac10dedd4cd7bb52a90.gif',
'//www.qingtianseo.com/usr/uploads/auto_save_image/303721c6bbfe3e84665dc39b0017d15b.png',
'//www.qingtianseo.com/usr/uploads/auto_save_image/5089e8838896b04d8de64b51250e6951.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);
                    }
                })
            );
        })
    );
});

另一种程序的原理是,把数据库的内容,和模板页面的信息,缓存成一个php 文件,

然后,打开时,直接读取这个php的缓存,就像读取一个txt文本一样,只不过,这个php缓存,是以静态模板页面的形式存在!

所以网站是秒开的,

最后编辑:2022年08月03日 ©著作权归作者所有

猜你喜欢

发表评论