html5 – 在ServiceWorker中访问indexedDB.比赛条件

前端之家收集整理的这篇文章主要介绍了html5 – 在ServiceWorker中访问indexedDB.比赛条件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在ServiceWorker中展示indexedDB的示例并不多,但我看到的结构都是这样的:
  1. const request = indexedDB.open( 'myDB',1 );
  2. var db;
  3.  
  4. request.onupgradeneeded = ...
  5.  
  6. request.onsuccess = function() {
  7. db = this.result; // Average 8ms
  8. };
  9.  
  10.  
  11. self.onfetch = function(e)
  12. {
  13. const requestURL = new URL( e.request.url ),path = requestURL.pathname;
  14.  
  15. if( path === '/test' )
  16. {
  17. const response = new Promise( function( resolve )
  18. {
  19. console.log( performance.now(),typeof db ); // Average 15ms
  20.  
  21. db.transaction( 'cache' ).objectStore( 'cache' ).get( 'test' ).onsuccess = function()
  22. {
  23. resolve( new Response( this.result,{ headers: { 'content-type':'text/plain' } } ) );
  24. }
  25. });
  26.  
  27. e.respondWith( response );
  28. }
  29. }

ServiceWorker启动时可能会失败,如果是这样,在ServiceWorker中访问indexedDB的有效方法是什么?

解决方法

每次ServiceWorker启动时打开IDB都不太可能是最佳的,即使不使用它也会打开它.而是在需要时打开数据库.单例在这里非常有用(参见 https://github.com/jakearchibald/svgomg/blob/master/src/js/utils/storage.js#L5),因此如果它在其生命周期中使用了两次,则不需要打开IDB两次.

“激活”事件是打开IDB并允许任何“onupdateneeded”事件运行的好地方,因为旧版本的ServiceWorker已经不在了.

猜你在找的HTML5相关文章