14. The pixel pipeline
If you change a “layout” property, so that’s one that changes an element’s geometry, like its width, height, or its position
with left or top, the browser will have to check all the other elements and “reflow” the page. Any affected areas will need to
be repainted, and the final painted elements will need to be composited back together. ( web performance is avoid reflow )
If you changed a “paint only” property, like a background image, text color, or shadows, in other words one that does not
affect the layout of the page, then the browser skips layout, but it will still do paint (repaint).
If you change a property that requires neither layout nor paint, and the browser jumps to just do compositing.
15. Reduce the Scope and Complexity of Style
Calculations
Computed Style Calculations: Changing the DOM, through adding and removing elements,
changing attributes, classes, or through animation, will all cause the browser to recalculate
element styles and, in many cases, layout (or reflow) the page, or parts of it. This process is
called computed style calculation.
● The first part of computing styles is to create a set of matching selectors, which is
essentially the browser figuring out which classes, pseudo-selectors and IDs apply to any
given element.
● Figuring out how what the end result of an element with multiple rules is.
Reduce Style Calculations
● Reduce the complexity of your selectors; use a class-centric methodology like BEM
● Reduce the number of elements on which style calculation must be calculated.
16. Avoid Large, Complex Layouts and Layout
Thrashing
Similarly to style calculations, the immediate concerns for layout cost are:
● The number of elements that require layout.
● The complexity of those layouts.
Improvement:
● Avoid layout wherever possible
● Use flexbox over older layout models
● Avoid forced synchronous layouts
17. Avoid layout wherever possible
When you change styles the browser checks to see if any of the changes require layout to be
calculated, and for that render tree to be updated. Changes to “geometric properties”, such as
widths, heights, left, or top all require layout.
Layout is almost always scoped to the entire document. If you have a lot of elements, it’s going
to take a long time to figure out the locations and dimensions of them all.
If it’s not possible to avoid layout then the key is to once again use Chrome DevTools to see how
long it’s taking, and determine if layout is the cause of a bottleneck.
Note: Want a definitive list of which CSS properties trigger layout, paint, or composite? Check out CSS
Triggers.
18. Use flexbox over older layout models
The web has a range of layout models, some being more widely supported than others. The
oldest CSS layout model allows us to position elements on screen relatively, absolutely, and by
floating elements.
19. Avoid forced synchronous layouts - layout
thrasing
First the JavaScript runs, then style calculations, then layout. It is, however, possible to force a
browser to perform layout earlier with JavaScript. It is called a forced synchronous layout.
● Batch edit HTML elements
● Avoid layout thrasing, force sync layout
23. Improve Rendering blocking CSS
● Don’t add css via @import rule
The @import rule lets you import CSS from other stylesheets, but this causes the browser
to process your CSS file more slowly because it also has to download the imported files.
Until this takes place, the rendering process will be blocked.
● Use the media attribute for conditional CSS
By default, the browser treats all CSS files as render blocking resources.
Even though these files are still download on all devices, they become non-render
blocking resources if the condition evaluates as false.
● Use font-display property
● Preload, non-critical resource ...
24. Improve Rendering blocking CSS
● Don’t add css via @import rule
The @import rule lets you import CSS from other stylesheets, but this causes the browser
to process your CSS file more slowly because it also has to download the imported files.
Until this takes place, the rendering process will be blocked.
● Use the media attribute for conditional CSS
By default, the browser treats all CSS files as render blocking resources.
Even though these files are still download on all devices, they become non-render
blocking resources if the condition evaluates as false.
25. HTTP Caching
● Weak Caching Header: Etag và Last-Modified
● Strong Caching Header: Expires và Cache-Control
26. Optimizing Javascript Execution
- Avoid setTimeout or setInterval for visual updates; always use requestAnimationFrame
instead.
- Move long-running JavaScript off the main thread to Web Workers.
- Use micro-tasks to make DOM changes over several frames.
- Use Chrome DevTools’ Timeline and JavaScript Profiler to assess the impact of
JavaScript.
Tại sao Tốc độ lại quan trọng ?
Người dùng ngày càng dựa vào thiết bị di động để truy cập nội dùng và dịch vụ trên web.
Nếu chung ta xem việc phân tích trang web có thể sẽ biết được chính xác trang web của mình đang diễn ra như thế nào, tiêu tốn bao nhiêu data của người dùng.
Người dùng ngày càng đòi hỏi cao hơn về khả năng trải nghiệm trên trang web của chúng ta, và họ có thể so sánh và lựa chọn những dịch vụ hoặc trang web họ cảm thấy thích.
The DOM and CSSOM trees are combined to form the render tree.
Render tree contains only the nodes required to render the page.
Layout computes the exact position and size of each object.
The last step is paint, which takes in the final render tree and renders the pixels to the screen.
To construct the render tree, the browser roughly does the following:
Starting at the root of the DOM tree, traverse each visible node.
Some nodes are not visible (for example, script tags, meta tags, and so on), and are omitted since they are not reflected in the rendered output.
Some nodes are hidden via CSS and are also omitted from the render tree; for example, the span node---in the example above---is missing from the render tree because we have an explicit rule that sets the "display: none" property on it.
For each visible node, find the appropriate matching CSSOM rules and apply them.
Emit visible nodes with content and their computed styles.
visibility: hidden is different from display: none.
Layouting- Kết quả cuối cùng xuất ra render tree là cả content và style nội dung, và chuyển qua stage “layout”
Tới bước này thì đã tính toán được các node sẽ được hiển thị và computed style. Nhưng chúng ta chưa tính toán chính xác vị trí và kích thước của nó trên độ rộng thực tế của màn hình thiết bị - Bước này gọi là “Layout” hay còn gọi là “reflow”.Trình duyệt sẽ duyệt qua cả cây và bắt đầu tự node gốc để tìm ra kích thước và vị trí của từng đối tượng.
- Kết quả của quá trình layout Box Model, ghi lại chính xác kích thước của từng đối tượng trên màn hình và chuyển đổi thành đơn vị pixel tuyệt đối trên màn hinh.
- Kết thúc của quá trình Layout thì ta thấy được kích thước, vị trí, kiểu dáng màu sắc của đối tượng. Và sẽ chuyển đổi mỗi node ở render tree sang chính xác pixel sẽ hiển thị trên màn hình.paint hay còn gọi là rasterizingPainting is the process of filling in pixels. It involves drawing out text, colors, images, borders, and shadows, essentially every visual part of the elements. The drawing is typically done onto multiple surfaces, often called layers.Demo Chrome Dev tool :D any url
JS change/ thuc hien tac vu update UI nao do => trigger lai qua trinh tinh toan lai layout va thay doi LayoutStyle Calculation: ở quá trình này, tìm ra các css rule áp dụng cho phần tử dựa trên những bộ chọn. và sau đó no sẽ tính toán style dựa trên những giá trị css rule này.
Layout: Khi trình duyệt biết được quy tắc nào áp dụng cho phần tử, nó bắt đầu tính toán kích thước, vị trí của đối tượng. Các phần tử thường ảnh hưởng lẫn nhau, vì vậy nó sẽ phải tính toán liên tục => quá trình này rất tốn performancePaint: is the process of filling in pixels. It involves drawing out text, colors, images, borders, and shadows, essentially every visual part of the elements. The drawing sẽ vẽ trên nhiều layer ( lớp )Composite: paint được vẽ thành nhiều lớp có khả năng nên chúng cần được vẽ ra màn hình theo đúng thứ tự để trang hiển thị chính xác. Điều này đặc biệt quan trọng đối với các phần tử chồng lên nhau
Style Calculations: Trinh duyệt sẽ tìm tất cả style sẽ apply cho phần tửTwo part:- Tìm ra tất cả matching selector - Tìm ra kết quả cuối cùng là với phần tử đó những rule nào sẽ được applVì vậy để giảm tình toán style chúng ta thường áp dụng: - Giảm độ phức tạp của selector ( Vì selector đi từ phải sang trái, travelse selector càng phức tạp thì trình duyệt càng tốn cost/time để thực hiện việc tìm kiếm selector) [DEMO]- Giảm số phần tử sẽ phải tính toán style. Vì việc tính toán style là sync-chronous. Thằng tới sau phải chờ thắng trước complete mới tới luot => càng nhiều phần tử cần tính toán style thì việc render cầng chậm
Hạn chế kích hoạt tính toán layout
Dung flexbox
Han che kich hoat layout som
Hạn chế kích hoạt tính toán layoutViệc thay đổi một số thuộc tính CSS của element có thể kích hoạt browser tính toán lại layout của element đó.Khi một element bị thay đổi layout thì thường là các element khác cũng sẽ bị thay đổi theo (kích thước, vị trí…). Do đó nếu trang của bạn có nhiều element và việc kích hoạt layout diễn ra quá thường xuyên thì hoàn toàn không tốt cho performance.css trigger => Bạn có thể sử dụng Chrome DevTools để kiểm tra xem web page của bạn có bị kích hoạt layout quá nhiều hay không.
CSS3 có cung cấp một số thuộc tính mới không những giúp chúng ta canh chỉnh layout dễ hơn mà còn giúp tăng hiệu suất rất nhiều. Điển hình là Flexbox, việc sử dụng flexbox để canh chỉnh layout sẽ dễ hơn so với cách dùng float truyền thống.
Run JS, tinh1 toan style => layout. Tuy nhien có thể do coding mà việc thực hiện layout được thuc thi truoc ( thằng trước chưa xong thằng sau đã tới)
Thay doi hang loat => batching edit
Tranh reflow vong lap
https://betterprogramming.pub/web-performance-dom-reflow-76ac7c4d2d4f
T0 and T1 captures the network and server processing times. ( speed tuy theo size of file )
Demo
Tương tư như defer trong javascipt loading.
Sử dụng import rule sẽ làm CSS chậm hơn bởi vì phải tải file import tuần tự. Nghĩa là tải file import trước, sau đó tải file css. DemoSử dụng media attribue để filter cssMặc định CSS file là render blocking resource. Nghìa là trong quá trình parse html, khi gặp css quá trình render sẽ bị dừng lại chờ tới khi css tải xong.Nếu thêm thuộc tính này, tất cả css vẫn được tải về, nhưng sẽ trở thành không chặn render nếu condition false.
Democss-import
css-media
font-display
Sử dụng import rule sẽ làm CSS chậm hơn bởi vì phải tải file import tuần tự. Nghĩa là tải file import trước, sau đó tải file css. DemoSử dụng media attribue để filter cssMặc định CSS file là render blocking resource. Nghìa là trong quá trình parse html, khi gặp css quá trình render sẽ bị dừng lại chờ tới khi css tải xong.Nếu thêm thuộc tính này, tất cả css vẫn được tải về, nhưng sẽ trở thành không chặn render nếu condition false.
Demo
HTTP Caching xảy ra khi trình duyệt lưu lại các bản sao của các tài nguyên(ví dụ như cái file css, js, ảnh) để phục vụ cho những request tiếp theo. Điều này giúp giảm tải cho các máy chủ không phải xử lí quá nhiều request từ các client khác nhau và cải thiện tốc độ của website khi các tài liệu được lấy về một cách nhanh hơn, giúp người dùng có trải nghiệm tốt hơn.Strong Caching: là giải pháp phải request lên server để check sự thay đổi của các tài nguyên, Weak Ngược lại ko cầnLast-Modified Khi lần đầu tiên thực hiện việc request lên server để lấy tài nguyên(ví dụ như file logo.png). File này chưa được cache lại nên server trả về file logo.png kèm theo tham số Last-Modified ở response để xác định thời điểm cuối cùng thay đổi của file này.
Trong lần tiếp theo request lên server để lấy file logo này. Client gửi kèm tham số If-Modified-Since, là giá trị của tham số Last-Modified lần trước nhận được. Server kiểm tra tham số này nếu trùng với thời gian thay đổi trên server thì sẽ trả về code 304 Not Modified để báo cho client biết file này không có gì thay đổi, có thể sử dụng file bản sao đã được lưu ở cache trình duyệt.
Client: Lấy cho tao file logo có tên logo.png
Server: Tao gửi file logo kèm tham số Last-Modified lưu thông tin về lần thay đổi cuối cùng của file nàyEtag If-None-Match và response Header Etag
expires 5m; // Xác định file này hết hạn trong vòng 5 phút. Mặc kệ client có request lên server hay không ?
cache-control: no-storeno-cache
max-age
Demo
Text Content Minify Code, Compress Text Resource Gzip …Gzip -> vào link kéo xuống tool check
https://developers.google.com/web/fundamentals/performance/rendering/optimize-javascript-execution60 FPS => 1000/60 = 16ms de thuc hien cac tinh toan perframeNeuĐể làm được điều này bạn cần dùng hàm requestAnimationFrame. Hàm này có chức năng “hẹn giờ” chạy vào đúng thời điểm của frame tiếp theo.
“micro-task”: Web Workers không thể tương tác với DOM tree, => chia nhỏ task ra, sau đó sử dụng requestAnimationFrame để cập nhật UI. Lúc này, nếu mỗi task nhỏ có thời gian thực thi bé hơn 16ms thì sẽ tránh được hiện tượng giật, lag như khi chạy cả task lớn.Su dung Chrome dev tool de dieu tra javascript