Houdini: Perhaps the most exciting CSS evolution you have never heard of

  css, css3, html5

Original link:Houdini: Maybe The Most Exciting Development In CSS You’ve Never Heard Of
More translations will be released one after another. Welcome to praise+collection+Watch my columnTo be continued.

Have you ever wanted to use some special CSS features, but becauseNot supported by all browsersAnd choose to give up? Or are these features supported by all browsers, but always accompanied by strange bugs, inconsistent or even contradictory performance? If all this has happened to you-I bet-you should pay attentionHoudini.

Houdini is a new task of W3C, whose aim is to solve the above-mentioned problems. It plans to provide a series of API to enable developers to customize and extend CSS, and put these styles directly into the browser’s rendering engine to render.

But what does this actually mean? Is this really a good idea? And how will it help us develop modern and future-oriented pages?

In this article, I will try to answer the above questions. Before that, it is very important to understand what problems exist today and what changes need to be made. Later, I will explain in more detail how Houdini solved the problem and list some cool features encountered in the current development process. At the end of the article, I will provide some practical ways for us web developers to make Houdini a reality.

What problem does Houdini want to try to solve?

Every time I write an article or make a DEMO to show some new CSS features, it is inevitable that someone will always comment or leave a message on Twitter saying, “it’s really cool and crazy! But the bad thing is that we won’t be able to use them for the next ten years. “

Just like the negative comments above, which are full of negative energy and without constructive comments, I deeply think so. In history, drafts with new features were generally accepted only after many years. Because of this, and after looking at the history of the development of the web, the only way to make the new feature draft really CSS standard is to let it go through the standard process.

标准流程
Every step in the standard process

I cannot resist this so-called standard process, but I must admit that it wastes a lot of time!

For example,flexboxThe first proposal was made in 2009, but developers are still complaining that they cannot use it until now because only a few browsers support this feature. Fortunately, as most browsers support automatic updates, this problem is slowly improving. However, even with a modern browser, there is still a delay between the draft and becoming a usable standard.

Interestingly, this is not a problem in all areas of web development. Let’s look at how Javascript does it:

js方案
Steps to write polyfill in Js

Under such circumstances, it usually takes only a few days for a plan to be conceived and used in a production environment. I mean, I already use it in the production environment.async/awaitMethod, even if this method is not supported by any browser!

You can also feel the great emotional difference between the two communities. In the Javascript community, you will see some articles complaining that JS is developing too fast. On the contrary, in the CSS community you will hear some exclamations that it is futile to learn any new features before they can be used.

So, why don’t we write some CSS polyfill ourselves?

At first glance, polyfill writing CSS seems to be a ready-made answer. With excellent polyfill, CSS will develop as fast as Javascript, right?

Unfortunately, this is not that simple. Polyfill for CSS is very difficult, and it often destroys all performance.

Javascript is a dynamic language, which means you can use JS to polyfill itself. Because of its dynamic characteristics, it is very easy to expand. On the other hand, CSS can hardly be filled by itself. In some cases, you can implement CSS polyfill (POSTCSSThis is what I do). However, when you want polyfill anything that depends on the DOM structure, or the style or location of an element, you have to run your polyfill logic on the client.

Unfortunately, it is difficult for browsers to meet this requirement.

The following picture shows the basic process of the browser from receiving to rendering an HTML document. The blue area is the step that Javascript has the ability to control:

xx
Javascript Control in Browser Rendering Process

This picture is quite depressing. As a developer, you cannot control how browsers parse HTML and CSS into DOM andCSS object model (CSSOM)Of; Unable to control the entire rendering process; It is impossible to control how the browser chooses to render elements onto the DOM or how to fill content onto the screen to present to the user. You also have no control over how the browser is typeset.

The only thing you can completely control is DOM. At this time CSSOM is available; Even so, to quote a sentence from Houdini website, this is “lame, inconsistent between browsers, lack of demonstration features.”

For example, CSSOM in today’s browsers won’t tell you the rules of cross-domain style sheets, and it is easy to discard CSS syntax or declarations that it doesn’t understand-which means that you can’t use CSSOM when you want to polyfill some features that browsers don’t support. Instead, you can only manually traverse DOM and find it<style>Or (and)<link>Tag, parse it, rewrite it, and add it back to DOM.

Of course, updating DOM means that the browser will completely redraw the layout, drawing and typesetting process.

x
Using Javascript to polyfill in Browser Rendering Stage

When rendering the page completely, it may not cause such a big performance impact (especially for some websites), and it is not necessary to consider the possibility of occurrence. If your polyfill logic needs to be implemented in the event response, such as scrolling event, window size change event, mouse movement event, keyboard event-when these things happen all the time-the performance impact will be very large, sometimes even jamming and collapse.

Even worse, you will find that most CSS polyfill now includes their own CSS parser and running logic. At the same time, because parsing and running are very complicated things, these polyfill are either too large or too prone to bugs.

To sum up, if you want your browser to do something it doesn’t know how to do (such as using your custom CSS), then you must disguise some instructions to the browser, which can be done by manually updating and modifying DOM. In addition, you have no way to affect other stages of the rendering process.

In this case, why didn’t I think of modifying the rendering engine inside the browser?

To me, this question is the key to this article. If you only skim the previous content, please read the following paragraph carefully.

After the previous section, I’m sure some readers are already thinking, “I don’t need this! I’m just making ordinary pages. I’m not going to hack the browser or get some creative, experimental, cutting-edge products or anything like that. “

If you think so, I strongly suggest you review the development history of the technologies you used in development over the years. The idea of wanting to be able to enter and modify the browser style rendering process is not for the cool demo-it is to give developers or frameworks greater rights to do two main things:

  • Eliminate differences between browsers for defined styles

  • Invent or polyfill new properties so that people can use them today.

If you have ever used Javascript libraries such as jQuery, you have benefited from it! In fact, this is the selling point of almost all front-end libraries and frameworks today. The five most popular Javascript and DOM operating frameworks on Github-Angular JS, D3, JQuery, React, and EMBER-all do a lot of work for browser compatibility, thus eliminating the need to consider browser compatibility at your root. They can be used directly through the API provided to the outside.

Now, let’s return to CSS and its cross-browser compatibility issues. Even popular CSS frameworks such as Bootstrap and Foundation, which claim to advocate compatibility, cannot avoid cross-browser bugs-they just avoid bugs rather than solve them. At the same time, the bug brought by CSS across browsers is not just a thing of the past. Even today, in the face of new features such as flexbox, we still face the inconsistency problem brought by cross-browser.

Finally, imagine how comfortable your development experience will be if you are sure that you can use any CSS property and that they work properly in different browsers. Imagine again that any new features you hear on blogs and conferences-such as CSS grids, CSS snap points and sticky positioning-can work perfectly like native CSS in some way. All you need to do is copy a piece of code from Github, which would be wonderful.

This is exactly Houdini’s goal and this is exactly the future for which his organization is striving.

Therefore, even if you are not planning to write CSS polyfiles or develop a new experimental feature, you are likely to expect others to do it-because once these polyfiles are implemented, everyone will benefit from it.

What exactly is Houdini in the current development?

As I mentioned above, developers have only a little right to operate the browser rendering process. Indeed, only DOM and CSSOM can be operated by developers.

In order to solve this problem, Houdini team provided some new methods, allowing developers to enter other steps in the rendering process for the first time. The following picture shows the rendering process and how the new method is used to modify the steps. (Note that the gray part of the method is planned but still being modified. )

xx
Houdini’s New Method Affects the Position of Browser Rendering Process

The next few sections will briefly introduce each new method and its functions. What I want to say is that there are still some new methods that have not been included in this article. Please refer to the complete list of methods.GitHub repository of Houdini’s drafts.

CSS properties-value apis

CSS can already customize properties, as I said before, I am very excited about the possibility of realizing this.CSS properties-value apisIt is also a step forward for custom attributes, making them more practical when adding attribute operations.

There are many great things that can be implemented in custom attributes, but perhaps the biggest selling point is to enable developers to use custom attributes that are not currently supported in transition and animate.

Imagine the following example:

body {
 --primary-theme-color: tomato;
 transition: --primary-theme-color 1s ease-in-out;
 }
 body.night-theme {
 --primary-theme-color: darkred;
 }

In the above code, ifnight-themeAdded to<body>Among them, then all elements in the page will be able to reference--primary-theme-colorThe value of the property, and slowly from thetomatoTransition todarkred. If you want to do this now, you have to manually add these transition codes for each element, because you can’t let them finish the work automatically.

Another established feature of this API is that it will allow registration of a “call hook”, a method that allows developers to modify the final value of custom attributes after the rendering process is completed. This method will be very useful when polyfill.

CSS TYPED OM

CSS TYPED OMCan be considered the current CSSOM version 2.0. Its goal is to solve a large number of specifications at this stage, as well as problems brought about by new CSS parsing API and CSS attribute-value API.

Another goal is to improve performance. Transforming the current CSSOM into a meaningful JS expression can greatly improve performance.

CSS LAYOUT API

CSS LAYOUT APIAllows developers to customize layout modules. “Layout module” refers to any module with CSSdisplayThe element of the attribute. This will be the first time that developers will be brought with performance comparable to native layouts, such asdisplay: flexAnddisplay: table.

As an example of actual use,Masonry layout libraryIt shows how developers want to achieve complex and amazing layouts, but cannot achieve them through CSS alone.

Unfortunately, they are troubled by performance problems, especially on some less capable equipment.

CSS LAYOUT API provides aregisterLayoutThe method gives developers the name of a layout as a parameter (a name that will be used in CSS later) and a Javascript class that contains all the layout logic. What is shown here is a passageregisterLayoutAPI registrationmasonryBasic examples of layout.

registerLayout('masonry', class {
 static get inputProperties() {
 return ['width', 'height']
 }
 static get childrenInputProperties() {
 return ['x', 'y', 'position']
 }
 layout(children, constraintSpace, styleMap, breakToken) {
 // Layout logic goes here.
 }
 }

If you don’t understand the above code, it doesn’t matter. The most important thing is the following example, whenever you putmasonry.jsThe file is referenced to your page, you can write CSS like this and everything will work normally:

body {
 display: layout('masonry');
 }

CSS PAINT API

This API is very much like the LAYOUT API mentioned above. It provides aregisterLayoutMethods. Developers are able to
CSS can be used anywherepaint()Method, the next picture will be generated and placed on the registered name.
Here is a simple example depicting a circle with color:

registerPaint('circle', class {
 static get inputProperties() { return ['--circle-color'];  }
 paint(ctx, geom, properties) {
 // Change the fill color.
 const color = properties.get('--circle-color');
 ctx.fillStyle = color;
 // Determine the center point and radius.
 const x = geom.width / 2;
 const y = geom.height / 2;
 const radius = Math.min(x, y);
 // Draw the circle \o/
 ctx.beginPath();
 ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
 ctx.fill();
 }
 });

You can use this in CSS:

.bubble {
 --circle-color: blue;
 background-image: paint('circle');
 }

Now.bubbleThe elements will be displayed with a blue circle as the background. No matter what happens, this circle will be equally centered in the elements.

WORKLETS

Most of the API mentioned above is shown through code blocks (for exampleregisterLayoutAndregisterPaint)。 If you want to know where the code should run, the answer isWORKLETIn the script.

Worklets are like web workers. They allow you to refer to script files and run Javascript code at any time during the rendering process. At the same time, they are independent of the main thread.

Worklet scripts strictly restrict what you can do, which is the key to high performance.

Composite Scrolling and Animation

Even so far there is still no information oncomposited scrolling and animationHowever, this is indeed one of Houdini’s most widely known and not very promising features. The last API allows developers to run logic in the worklet, which is responsible for typesetting and is separate from the main thread. It also supports modifying the attribute values of a subset of DOM elements. This subset contains only the attributes that can be read and written, but does not force the rendering engine to recalculate the layout or style (for example, transform, opacity, scroll offset, etc.). )

This will allow developers to create high-performance animation based on scroll- and input- such assticky scroll headers and parallax effects. You can find more on Github about the problems this API is trying to solve.Example.

Even though there is still a lack of official documents, experienced developers have already started to try them in Chrome browser. In fact, the Chrome team has recently started to implement it based on these API that will eventually be released.CSS snap pointsAndsticky positioning. This is really exciting because it means that the Houdini API has enough performance to enable the new Chrome features to be implemented based on them. If you are still worried that Houdini is not as efficient as the original, the above facts may dispel your doubts to some extent.

Look at real examples.SurmaHas released avideo, showing a demo running inside a Chorme-based browser. Demo imitated the user’s avatar change behavior animation of the native Twitter APP. Do you want to know how it is realized? Please look at itSource code.

Now, what can you do?

According to the above, I think any web developer should care about Houdini;; It will make our development career more convenient. Even if you have never directly used Houdini, you probably have already used something developed based on it.

Although this future will not come soon, it is likely to be closer than we thought. Representatives of all mainstream browser suppliers gathered at the last Houdini face-to-face meeting early this year and reached a basic consensus on how to establish and develop Houdini.

What I can say is not whether Houdini can be finally realized, but when and where everyone can participate.

Browser providers, like any software developer, must focus on developing new features. Moreover, priority is often given to the development of new features that regular users emphasize.

Therefore, if you are concerned about the expansion of styles and layouts in web development, and if you want to directly use the new CSS features without waiting for a long time, please tell the development members of the browser you are using.

Another area where you can contribute is to develop some real and usable cases-for example, to implement some styles or layouts that are difficult to implement today. How many are there on Github?Actual case, you can submit and publish pull request to contribute your ideas. If the document does not exist, you can create a new one.

Members of the Houdini team (generally called W3C) are looking forward to ideas and suggestions from developers. Any person involved in standard setting is a browser development engineer. They are usually not professional web developers, which means they do not always know where the pain is.

They need us to tell them.

Reference material

Special thanks to members of Houdini Ian Kilpatrick and Shane Stephens for reviewing this article.


The article is full of content and has not been checked and proofread with high quality. Only the original text shall prevail. Please point out any mistakes or omissions.
Not regularly publish development experience, learning experience, dry goods outside the wall, welcome to pay attention to my column.
Thank you for reading, I am Jrain, see you next time!