惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

美团技术团队
W
WeLiveSecurity
Stack Overflow Blog
Stack Overflow Blog
L
LangChain Blog
S
SegmentFault 最新的问题
Apple Machine Learning Research
Apple Machine Learning Research
Google DeepMind News
Google DeepMind News
F
Full Disclosure
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Register - Security
The Register - Security
G
Google Developers Blog
C
Check Point Blog
GbyAI
GbyAI
A
About on SuperTechFans
V
Vulnerabilities – Threatpost
T
The Blog of Author Tim Ferriss
T
Tor Project blog
AWS News Blog
AWS News Blog
Cyberwarzone
Cyberwarzone
C
CERT Recently Published Vulnerability Notes
MongoDB | Blog
MongoDB | Blog
Latest news
Latest news
aimingoo的专栏
aimingoo的专栏
U
Unit 42
Y
Y Combinator Blog
P
Privacy International News Feed
Cisco Talos Blog
Cisco Talos Blog
S
Securelist
S
Schneier on Security
雷峰网
雷峰网
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Attack and Defense Labs
Attack and Defense Labs
P
Proofpoint News Feed
C
Cisco Blogs
Webroot Blog
Webroot Blog
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
月光博客
月光博客
P
Privacy & Cybersecurity Law Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
罗磊的独立博客
Cloudbric
Cloudbric
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Hacker News: Ask HN
Hacker News: Ask HN
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - 司徒正美
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Microsoft Security Blog
Microsoft Security Blog

Example blog

Ghost routing explained with routes.yaml examples — routes, collections & taxonomies Ghost redirects explained with practical redirects.yaml examples How to Serve JSON or XML Data in Ghost How to Change Your Default Post Template in Ghost Ghost Custom Theme Settings How to add Google Fonts to Ghost Themes How to Configure Ghost with Mailgun Ghost Theme Structure & Organization How to Make Custom Templates in Ghost Themes How to Install Ghost CMS via Ghost-CLI How to Add Syntax Highlighting to Ghost The best Ghost CMS hosting platforms Ghost 6.0 — Social Web and Native Ghost Analytics Ghost CMS Social web beta, email 2FA and more author social links How to keep custom design settings when updating your Ghost theme How to use the public preview card in Ghost How to add members-specific sections in Ghost How to customize the default content CTA in Ghost How to build a custom homepage in Ghost An overview of Ghost editor cards and and how they work Ghost CMS News: One-time payments & collecting sales tax How to customize the private site access template in Ghost How to add custom fonts in Ghost themes Ghost CMS News: Additional payment methods & internal linking How to use Code Injection in Ghost How to set meta data of your custom routes & collections in Ghost Ghost CMS News: TK reminders, ActivityPub and improvements How to format dates and use the date helper in Ghost Ghost CMS internationalization, custom fonts & spam protection Understanding and optimizing post and page settings in Ghost CMS Trigger the Ghost Portal popup based on page scroll progress How to Deploy Your Ghost Theme with GitHub Actions How to create a custom recommendations page for your Ghost CMS theme Ghost CMS News: New editor, refreshed settings & recommendations Ghost CMS News: Source - the new default theme and native image editing How to Add Different Logos for Dark & Light Themes in Ghost Upgrade to Node v18 for Ghost CMS & common errors Ghost Snippets: Adding Schema markup in Ghost How to add a scroll-based progress bar to your Ghost CMS site How to Create a Custom Navigation Template in Ghost How to Segment Subscribers with Member Labels in Ghost The best way to create a contact page in Ghost How to Use the Ghost Subscription Forms in Your Theme & Posts How to update your Ghost site URL when self-hosting Ghost CMS News: Signup cards and better landing pages How to Add Breadcrumbs to Your Ghost Theme How to integrate the Applause Button into your Ghost theme How to Hide a Post From the Home Page in Ghost CMS Ghost CMS block and contentFor helper overview & tips How to add Image Lightbox to Ghost Themes Ghost CMS News: Signup form embed, new editor and bulk actions. Biron Themes becomes Bright Themes 🎉 How to Audit & Test a Ghost Theme How to Create Related Posts Section in Ghost How to Use Ghost Filter Expressions Ghost CMS newsletter settings and post analytics How to Update Your Ghost Theme When We Release New Versions Ghost CMS News: Automatic list cleaning & email troubleshooting How to Create a Featured Post Slider in Ghost How to Add Reading Time to Ghost Blog Posts How to Create a Post Archive for Your Ghost Theme Ghost CMS Price Helper Overview & Tips Self-Hosted Ghost CMS with DigitalOcean Ghost CMS News: Member Growth Sources & Audience Feedback How to Open External Links in a New Tab in Ghost How to Integrate Google Analytics with Ghost Ghost CMS News: History Log & Newsletter Analytics How to Automatically Add Member Labels From Referral Traffic in Ghost? Ghost CMS News: Free trials & email notifications Ghost CMS Match Helper Usage & Tips Ghost CMS News: Native Comments Ghost CMS News: Ghost Explore & Premium Newsletter Previews Ghost Snippets: Custom Progress Cards & Steps Ghost CMS News: Native Search The Best Ghost CMS Search Plugins & Libraries Ghost Snippets: Custom Stylish Tables How to Add a Scroll Top & Progress Indicator Button in Ghost Ghost Snippets: Accordions How to Add Tag Dropdown to Your Ghost Theme Ghost 5.0 released 🎉 Ghost Snippets: Custom Subscribe Forms Ghost Snippets: Custom Alert Boxes How to Show Post or Newsletter Issue Number in Ghost How to Self-Host Google Fonts in Ghost CMS Ghost CMS News: Membership, Tiers & Activity Feed Custom Pages in Ghost CMS Themes Ghost CMS Search Using Fuse.js Ghost CMS News: Offers and Discounts & New Cards Ghost CMS News: Membership tiers, email CTA & filters Ghost CMS News: Grammarly Support & Feature Image Captions. Ghost CMS News: Improved Member Accounts & Personalized Newsletter. Ghost 4.0 Launched With Native Newsletters & Membership Ghost CMS News: Cancellation Feedback & Newsletter Stats. Ghost CMS News: Improved Member Dashboard & Sidebar Views. Ghost CMS News: Google Pay support, email newsletters & secondary navigation Ghost CMS News: Member Support, Portal & Content Snippets. Ghost CMS News: Referral Programs & Responsive Images. Ghost 3.0 is here with brand new features Ghost 2.0 is here with new features How to Add Search to Ghost Using ghostHunter
Ghost Themes as Progressive Web Apps
Bright Themes · 2020-05-05 · via Example blog

Progressive Web Apps are web applications that have been designed with three main ideas behind: capability, reliability and installability. These main pillars make PWAs feel like a native application.

Once a Progressive Web App is installed it will run in a standalone window instead of a browser tab. They can be launched from the home screen and it's possible to search for them.

You can transform your Ghost theme into a progressive web app. Let's see how.

Requirements

In order to create a PWA from your ghost theme we need at least the following features:

  • Secure contexts (HTTPS)
  • Service Worker
  • manifest file

Secure contexts (HTTPS)

The application must be served over a secure network connection. Ghost comes with Let's Encript integration. For Ghost Pro users there is not configuration needed, while for self hosted Ghost Instances during installation you are asked if you want SSL setup.

In case you don't have an SSL Certificate you can run this command to start the setup:

ghost setup ssl

In general having SSL is not only a best practice, but it also establishes your web application as a trusted site.

Service workers

A service worker is a script that your browser runs in the background and it allows intercepting and control of how a browser handles its network requests and caching.

The service worker script is run separately from the web page. Using service workers, we are able to create an offline experience for our web app.

Manifest file

The web app manifest is a JSON file that tells the browser about your Progressive Web App and controls how the app appears to the user.

Typically manifest file includes the name of the app, the start ULR, the icons the app should use, and other details necessary to transform the website into app format.

Create the Service Worker

We will create a new file in the root folder of the ghost theme sw.js.

const PRECACHE = 'precache';
const RUNTIME = 'runtime';

// A list of local resources we always want to be cached.
const PRECACHE_URLS = ['/offline/'];

const OFFLINE_URL = ['/offline/'];

// The install handler takes care of pre caching the resources we always need.
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches
      .open(PRECACHE)
      .then((cache) => cache.addAll(PRECACHE_URLS))
      .then(self.skipWaiting()),
  );
});

// The activate handler takes care of cleaning up old caches.
self.addEventListener('activate', (event) => {
  const currentCaches = [PRECACHE, RUNTIME];
  event.waitUntil(
    caches
      .keys()
      .then((cacheNames) => {
        return cacheNames.filter(
          (cacheName) => !currentCaches.includes(cacheName),
        );
      })
      .then((cachesToDelete) => {
        return Promise.all(
          cachesToDelete.map((cacheToDelete) => {
            return caches.delete(cacheToDelete);
          }),
        );
      })
      .then(() => self.clients.claim()),
  );
});

// The fetch handler serves responses for same-origin resources from a cache.
// If no response is found, it populates the runtime cache with the response
// from the network before returning it to the page.
self.addEventListener('fetch', (event) => {
  // Skip cross-origin requests, like those for Google Analytics.
  if (event.request.url.startsWith(self.location.origin)) {
    event.respondWith(
      caches.match(event.request).then((cachedResponse) => {
        if (cachedResponse) {
          return cachedResponse;
        }

        return caches.open(RUNTIME).then((cache) => {
          return fetch(event.request)
            .then((response) => {
              // Put a copy of the response in the runtime cache.
              return cache.put(event.request, response.clone()).then(() => {
                return response;
              });
            })
            .catch((error) => {
              // Check if the user is offline first and is trying to navigate to a web page
              return caches.match(OFFLINE_URL);
            });
        });
      }),
    );
  }
});

That can seem a bit complicated so let's try and break it down.

  • PRECACHE and RUNTIME define the cache name.
  • PRECACH_URLS are the paths we want always to be cached. In this case we want the home page and a custom offline page to be pre cached.
  • OFFLINE_URL will be the URL we will redirect when a user tries to access a page(when offline) that is not cached. More about this later.

Then we have the service worker API events

  • install event, which takes care of pre caching the resources we always need (PRECACHE_URLS)
  • activate event, which takes care of cleaning up old caches
  • fetch event, which handles the server responses and populates the runtime cache and returns it

Create the manifest file

When creating the manifest file we have to consider the key properties.

  • short_name and/or name - You must provide at least the short_name or name property.
  • icons - When the PWA is installed the icons are used, depending of the device can be different sizes.
  • start_url - The start_url is required and tells the browser where your application should start when it is launched.
  • background_color - The background_color property is used on the splash screen when the application is first launched on mobile.
  • display - You can customize what browser UI is shown when your app is launched

More options and details can be found here.

Let's create the manifest.webmanifest file in the root folder.

{
  "name": "Auden Ghost Theme",
  "short_name": "Auden",
  "description": "Auden - a Magazine & Membership Ghost Theme",
  "lang": "en",
  "start_url": "/",
  "background_color": "#ffffff",
  "display": "standalone",
  "theme_color": "#e50b4f",
  "icons": [
    {
      "src": "/assets/icon-192x192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "/assets/icon-512x512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ]
}

You should change the property values for your website as well as add the icons and change the path/name if necessary.

Create offline page

To have a fallback when a user is offline and doesn't have a certain path cached, we can have a fallback page. For this create a new page in your Ghost Admin, call it Offline and make sure the Page URL is offline (or the value you provided in the service worker file).

You can define a message you want to appear on that page, for example: 'It looks like currently you are offline. Please try again when your network connection is available again.'

When you are done and the page is saved you can navigate to /offline and you should see your page.

Adapt the default.hbs file

This part can also be done using the Code Injection in Ghost Admin. After all the files are created we need to change the default.hbs file to link to our manifest and service worker files. First we need to adapt the content of the <head> tag, and add the following lines:

{{! PWA }}
<link rel='manifest' href='/manifest.webmanifest' />
<meta name='theme-color' content='#e50b4f' />
<link rel='apple-touch-icon' href='/assets/icon-192x192.png' />

Don't forget to replace the theme-color with your own and make sure to the icon exists.

And now for the service worker you have to add the following code before the closing </body> tag.

{{!-- Service Worker for PWA --}}
<script>
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.register('/sw.js');
    });
  }
</script>

This will reference our service worker.

Testing

Now that all is done (you can upload your modified theme), we can test if it's working. You can use Lighthouse either as Chrome extension, or by opening Developer Tools in your Chrome Browser (Ctrl+Shift+I) and go to the Audits tab and press Generate Report.

Lighthouse will analyze the whole website, besides the PWA check, it will also analyze the site's performance, accessibility, best practices and SEO.

You can see PWA live and working for our Auden Ghost Theme.

Here is the lighthouse report for it:

Auden Lighhouse report
Auden Lighhouse report

And a detailed PWA report by Lighthouse:

Auden Progressive Web App report
Auden Progressive Web App report

Live Demo

That's it, your Ghost Theme should work as a progressive web app now.

I hope you find this tutorial useful.