最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Service Worker Offline Caching Issue: Loading cached HTML files into object element does not load embedded images -

programmeradmin0浏览0评论

I have a web application where there's a main page index.html that contains a button. The button loads a separate page.html file into an <object> element on the main page. The page.html file contains an <img> element that needs to load while offline. I'm able to load page.html into the <object> while offline, however for some reason the image is not loading.

Is this something that's possible. If so, what do I need to do?

Here's a simple example of what I have:

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Offline Web App</title>    
    
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
        }
        button {
            padding: 10px 20px;
            margin: 20px;
            font-size: 16px;
        }
    </style>

</head>
<body>
    <h1>Offline Web App</h1>
    <button id="loadPage">Load Separate HTML Page</button>

    <object id="contentFrame" width="100%" height="400px"></object>


    <script>
        document.getElementById('loadPage').addEventListener('click', () => {
            document.getElementById('contentFrame').data = 'page.html';
        });
    </script>


    <script>
        if ('serviceWorker' in navigator) {
          window.addEventListener('load', () => {
            navigator.serviceWorker.register('service-worker.js')
              .then(registration => {
                console.log('Service Worker registered:', registration);
              })
              .catch(error => {
                console.error('Service Worker registration failed:', error);
              });
          });
        }
      </script>
</body>
</html>

service-worker.js:

const CACHE_NAME = 'offline-cache-v6';
const ASSETS_TO_CACHE = [
    '/app/index.html', // Main app page
    '/app/page.html', // Page loaded in <object>
    '/app/service-worker.js', // This file itself
    '/app/img.png' // Image on page.html
];

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => cache.addAll(ASSETS_TO_CACHE))
  );
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        if (response) {
          return response; // Return cached asset
        }

        return fetch(event.request)
          .then(response => {
            // Check if we received a valid response
            if(!response || response.status !== 200 || response.type !== 'basic') {
              return response;
            }

            // Clone the response.  A response is a Stream and already read.
            // We want to use it in the browser and in the cache.
            const responseToCache = response.clone();

            caches.open(CACHE_NAME)
              .then(cache => {
                return cache.put(event.request, responseToCache);
              });

            return response;
          });
      })
  );
});


self.addEventListener('activate', (event) => {
  const cacheWhitelist = [CACHE_NAME];

  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames.map((cacheName) => {
          if (cacheWhitelist.indexOf(cacheName) === -1) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

page.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page</title>
</head>
<body>
    <h2>This is a Separate HTML Page</h2>
    <img src="/app/img.png" alt="Cached Image" width="300">
</body>
</html>

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论