This article was posted on Tue, apr 24, 2018, 22:49, categorized as js instance. Read 1,363 times, 81 times today

By zhangxinxu from www.zhangxinxu.com/wordpress/?… This article can be reprinted in full, but need to retain the original author and source, the abstract drainage is optional.

The Service Worker provides the ability to fetch the requested resources, and then compile or transform them in the Service Worker to return other resources after processing. This feature can be used to realize the online client compilation of various resources. This paper will introduce the following two application cases. Show what the future of Web development might look like.

Service workers render pages with direct data and HTML templates

Many web pages are rendered directly from Node.js to achieve complete separation of the front and back ends, and this rendering is still done on the server side, but the rendering language is JavaScript.

In fact, with the Service Worker, we can render directly from the client side, i.e. the browser. The advantage is… At first glance, there is no special advantage, but the size of the HTML page is smaller, but this optimization of the size is like a small scratch, not worth mentioning. But then I thought, no, this HTML compilation is all done on the client side, which saves a lot of servers and a lot of money for the company, because it’s the user’s electricity.

And, after all, is another way to solve the problem, not sure some scenes can shine brilliantly, throw a brick to attract jade, focus on the ability to show.

Let’s start with a practical example, which you can click on here: Service Worker and client render HTML page demo

Open a look, is a list, and data or 2012 Beijing vegetable prices what ghost? First of all, the data stuff is not the focus, just from this article “JavaScript Interaction based on HTML templates and JSON data” to save time,

This page mystery to see the development file source code (right page source code are not) : github.com/zhangxinxu/…

As you can see, the index.html file source list is clearly the template syntax:

But when we right-click the page and look at the HTML source, we see the actual list content:

Why does this amazing thing happen? The trick is that the Service Worker does the HTML data rendering behind the scenes.

First, register the Service Worker with the following code:

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('./sw-reader.js', {
        scope: './'
    });
}Copy the code

Then the key is that sw-reader.js does two things:

  1. Built-in minimalist template rendering engine, using the old version of artTemplate, the size of only 2.3K. Screenshot below:

  2. capture.html, and template rendering of the obtained HTML character content, and return output. Complete the JS code as follows:
    self.addEventListener('fetch', function(event) { event.respondWith(async function () { if (/\.html/.test(event.request.url)) { let res = await fetch(event.request); let text = await res.text(); var data = {}; Text = text.replace(/([\w\ w]*?) // Filter JSON data so that it is not exposed to the user Parse ($1); < /script>/, function (matchs, $1) {// Get JSON data = json.parse ($1); return ''; }); Return new Response(template.compile(text)(data), {headers: {'content-type': 'text/html; charset=utf-8' } }); } return fetch(event.request); } ()); });Copy the code
  3. The variable text is the original HTML code, whereas in the Service Worker the rendered HTML code is returned as template.pile (text)(data), so the browser renders the final list data instead of the original template HTML.

In this demo, I put the JSON data required by the page in the header of the template page and marked it with

? ${ list: [] }? $Copy the code

It’s just not very elegant. Let’s look at another example of compiling static resources.

Second, Service Worker and browser directly CSS compilation

CSS Some pre-compiled tools, such as Less and Stylus, are compiled using JavaScript, which are available in web versions. Therefore, it is theoretically possible to transfer the compilation of Less and Stylus directly to the browser client, and then we do not need to load CSS files. Load the LESS file directly, compile it into CSS in the Service Worker and return it, and the page can be accessed normally.

The problem, however, is that the Web version of the Less Stylus is a bit bulky, with more than 150 K after compression, which personally feels a bit expensive.

In order to write quickly, I made a compilation tool named Qcss, can speak CSS declaration custom abbreviation, to achieve CSS code such as horse to fly swallow, for example:

.class-a { dib; w100; tc; }Copy the code

Can be converted in real time to:

.class-a {
  display: inline-block;
  width: 100px;
  text-align: center;
}Copy the code

This compiled JS method is very small, only a little over 2K, compared to the JS code amount of less, so it is very useful to use the Service Worker to implement a function that can compile CSS online.

For an example, you can click here hard: Qcss and Service Worker compiled into CSS demo in the browser

If we open the console and look at the network request, we will see that the page requests a QCSS file instead of a traditional CSS file:

The original QCSS file looks like this:

These are all abbreviations of some CSS attributes and attribute values. However, when we check the request data of qCSs. test in the demo page, it is the orthodox CSS code, as shown in the screenshot below:

Similarly, the Service Worker is compiled behind the browser. The core code of the JS file registered with the Service Worker is as follows:

Var QCSS =function(b){/* QCSS * /}; self.addEventListener('fetch', function(event) { event.respondWith(async function () { if (/\.qcss/.test(event.request.url)) { let res = await fetch(event.request); let text = await res.text(); return new Response(qcss(text), { headers: { 'content-type': 'text/css; charset=utf-8' } }); } return fetch(event.request); } ()); });Copy the code

Right? It’s easy to understand. It’s all the way.

What are the benefits of this online compilation? For example, the size of the test. QCSS file is 7 KB, while the size of the test. CSS file is 14 KB, which is 50% smaller than the size of the traditional CSS file. Note that the size of the compressed CSS is reduced by 50%.

Think about it, if all CSS of the company’s products become Qcss, the transmission is 30% to 50% smaller, it is estimated that the company can save a lot of traffic money.

For this purpose, I wrote a node. js tool that can convert CSS files into QCSS files: github.com/zhangxinxu/…

A compressor, a parser, and a Service Worker can subvert the current CSS resource loading strategy. For trivial projects like active pages, you can actually try this new technology and see its value.

About QCSS parsing and compression, I will introduce it when the time is ripe. Here, I will give you a broader idea of technical options and practices.

Service Worker and browser direct JS compilation

For example, we could move CoffeeScript directly into the browser, as above, without further expansion.

Fourth, concluding remarks

In theory, with a Service Worker, we can move a lot of Node.js capabilities to the client side and into the browser, not just offline caching, not just simulating and faking Ajax requests, but really doing whatever we want with a Service Worker.

With technical capabilities, all that remains is for our creativity and imagination to flourish our Web development strategy.

Again, the purpose of this article is to provide a starting point. The technical strategies of the two demos presented in this article are not necessarily optimal solutions, nor are they necessarily suitable for real projects, especially large projects, which may be risky. You are also welcome to pool your ideas and provide better and better related events. I will update this article in time.

The above –

Thanks for reading!

CSS World
Display my exclusive purchase code

// Want a tip? Click here. Got something to say? Click here.

    async
    await
    CSS Compression Tool
    fetch
    nodejs
    QCSS
    Service Worker