【问题标题】:PWA not working properly with Django using Service Workers使用 Service Worker 的 PWA 无法与 Django 一起正常工作
【发布时间】:2020-05-26 03:14:29
【问题描述】:

我在 django 中开发了一个小型原型,其中包含一个模型:Profile,以及带有 2 个视图(一个配置文件列表和一个编辑配置文件页面)的 2 个模板,以及 forms.py 中的一个表单。我想测试使用 Django 创建 PWA,这是我做的其他事情:1)pip install django-progressive-web-app,2)在已安装的应用程序中添加了“pwa”,3)为基础添加了渲染视图。将使用 service worker 的 html!

def base(request):
    return render(request,'app/base.html')

4) 将其添加到网址中:

urlpatterns = [
    path(r'', profiles, name="profiles"),
    path('user/<pk>', profile, name="profile"),
    path('', include('pwa.urls')),
]

5) 添加这个来识别服务工作者:

PWA_SERVICE_WORKER_PATH = os.path.join(BASE_DIR, 'posts/static/js', 'serviceworker.js')

6) 添加标签:

{% load pwa %}

<head>
    ...
    {% progressive_web_app_meta %}
    ...
</head>

7) 并将其添加到位于 app/static/js 中的 serviceworker.js 文件中:

var staticCacheName = 'djangopwa-v1';

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(staticCacheName).then(function(cache) {
      return cache.addAll([
        '/base_layout'
      ]);
    })
  );
});

self.addEventListener('fetch', function(event) {
  var requestUrl = new URL(event.request.url);
    if (requestUrl.origin === location.origin) {
      if ((requestUrl.pathname === '/')) {
        event.respondWith(caches.match('/base_layout'));
        return;
      }
    }
    event.respondWith(
      caches.match(event.request).then(function(response) {
        return response || fetch(event.request);
      })
    );
});

发生的事情是service worker在Chrome开发者工具下运行,但是在django控制台显示这个错误:Not Found: /base_layout,并且主页可以通过离线模式访问,但是其他路径(/user ) 不是。并且谷歌浏览器的控制台显示这个错误:

The FetchEvent for "http://localhost:8000/manifest.json" resulted in a network error response: the promise was rejected.
Promise.then (async)
(anonymous) @ serviceworker.js:19
serviceworker.js:1 Uncaught (in promise) TypeError: Failed to fetch

另外,图片没有被加载。

我做错了什么?

【问题讨论】:

  • 运行时您的 PWA 是否通过 Chrome Lighthouse 工具作为有效 PWA 传递?如果有问题,它通常会给出很好的提示。

标签: django django-templates progressive-web-apps


【解决方案1】:

对于图像,将图像 url 添加到传递给 cache.addAll 方法的数组中。像这样:

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(staticCacheName).then(function(cache) {
      return cache.addAll([
        '/base_layout',
        '/static/img-1.png',
        '/static/img-2.png',
      ]);
    })
  );
});

为确保加载您的 css 和 js 文件,还将它们的路径添加到数组中。

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    相关资源
    最近更新 更多