SlideShare una empresa de Scribd logo
1 de 27
Web
performance
jvinhit@gmail.com
Why does speed matter?
At the same time…Our applications are getting bigger.
How web page are born ?
DOM
CSSOM
Render-tree Construction, Layout, and Paint
Layout/ Paint
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.
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.
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
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.
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.
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
Rendering Blocking
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 ...
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.
HTTP Caching
● Weak Caching Header: Etag và Last-Modified
● Strong Caching Header: Expires và Cache-Control
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.
Reference
https://developers.google.com/web/fundamentals/performance/rendering/optimize-
javascript-execution

Más contenido relacionado

Similar a Web performance fundamental

Building high performing web pages
Building high performing web pagesBuilding high performing web pages
Building high performing web pagesNilesh Bafna
 
Organize Your Website With Advanced CSS Tricks
Organize Your Website With Advanced CSS TricksOrganize Your Website With Advanced CSS Tricks
Organize Your Website With Advanced CSS TricksAndolasoft Inc
 
ADF - Layout Managers and Skinning
ADF - Layout Managers and SkinningADF - Layout Managers and Skinning
ADF - Layout Managers and SkinningGeorge Estebe
 
Blooming SharePoint Design
Blooming SharePoint DesignBlooming SharePoint Design
Blooming SharePoint DesignKathy Hughes
 
Teams, styles and scalable applications
Teams, styles and scalable applicationsTeams, styles and scalable applications
Teams, styles and scalable applicationsVittorio Vittori
 
SEO Audit Report | Analyze Website Free 2023
SEO Audit Report | Analyze Website Free 2023SEO Audit Report | Analyze Website Free 2023
SEO Audit Report | Analyze Website Free 2023SEO Expert
 
"Responsive Web Design: Clever Tips and Techniques". Vitaly Friedman, Smashin...
"Responsive Web Design: Clever Tips and Techniques". Vitaly Friedman, Smashin..."Responsive Web Design: Clever Tips and Techniques". Vitaly Friedman, Smashin...
"Responsive Web Design: Clever Tips and Techniques". Vitaly Friedman, Smashin...Yandex
 
2009_09_11_Grid960
2009_09_11_Grid9602009_09_11_Grid960
2009_09_11_Grid960LightSpeed
 
KharkivJS: Flaws of the Web Components in 2019 and how to address them
KharkivJS: Flaws of the Web Components in 2019 and how to address themKharkivJS: Flaws of the Web Components in 2019 and how to address them
KharkivJS: Flaws of the Web Components in 2019 and how to address themVlad Fedosov
 
INTEGRATION (HTML/CSS) The technology behind AESTHETICS
INTEGRATION (HTML/CSS) The technology behind AESTHETICSINTEGRATION (HTML/CSS) The technology behind AESTHETICS
INTEGRATION (HTML/CSS) The technology behind AESTHETICSSiddharth Lale
 
Architecting with Style
Architecting with StyleArchitecting with Style
Architecting with StyleTimothy Knight
 
.NET 1.1 Base Page Framework Article
.NET 1.1 Base Page Framework Article.NET 1.1 Base Page Framework Article
.NET 1.1 Base Page Framework Articlebitburner93
 
Best practice for magento theming by shrikant vaghela
Best practice for magento theming by shrikant vaghelaBest practice for magento theming by shrikant vaghela
Best practice for magento theming by shrikant vaghelavijaygolani
 
Client side performance compromises worth making
Client side performance compromises worth makingClient side performance compromises worth making
Client side performance compromises worth makingCathy Lill
 
Structuring your CSS for maintainability: rules and guile lines to write CSS
Structuring your CSS for maintainability: rules and guile lines to write CSSStructuring your CSS for maintainability: rules and guile lines to write CSS
Structuring your CSS for maintainability: rules and guile lines to write CSSSanjoy Kr. Paul
 
CSS Methodology
CSS MethodologyCSS Methodology
CSS MethodologyZohar Arad
 
Frontend Performance: Illusions & browser rendering
Frontend Performance: Illusions & browser renderingFrontend Performance: Illusions & browser rendering
Frontend Performance: Illusions & browser renderingManuel Garcia
 
Lavacon 2014 responsive design in your hat
Lavacon 2014   responsive design in your hatLavacon 2014   responsive design in your hat
Lavacon 2014 responsive design in your hatNeil Perlin
 

Similar a Web performance fundamental (20)

Building high performing web pages
Building high performing web pagesBuilding high performing web pages
Building high performing web pages
 
Organize Your Website With Advanced CSS Tricks
Organize Your Website With Advanced CSS TricksOrganize Your Website With Advanced CSS Tricks
Organize Your Website With Advanced CSS Tricks
 
ADF - Layout Managers and Skinning
ADF - Layout Managers and SkinningADF - Layout Managers and Skinning
ADF - Layout Managers and Skinning
 
Blooming SharePoint Design
Blooming SharePoint DesignBlooming SharePoint Design
Blooming SharePoint Design
 
Teams, styles and scalable applications
Teams, styles and scalable applicationsTeams, styles and scalable applications
Teams, styles and scalable applications
 
SEO Audit Report | Analyze Website Free 2023
SEO Audit Report | Analyze Website Free 2023SEO Audit Report | Analyze Website Free 2023
SEO Audit Report | Analyze Website Free 2023
 
"Responsive Web Design: Clever Tips and Techniques". Vitaly Friedman, Smashin...
"Responsive Web Design: Clever Tips and Techniques". Vitaly Friedman, Smashin..."Responsive Web Design: Clever Tips and Techniques". Vitaly Friedman, Smashin...
"Responsive Web Design: Clever Tips and Techniques". Vitaly Friedman, Smashin...
 
2009_09_11_Grid960
2009_09_11_Grid9602009_09_11_Grid960
2009_09_11_Grid960
 
KharkivJS: Flaws of the Web Components in 2019 and how to address them
KharkivJS: Flaws of the Web Components in 2019 and how to address themKharkivJS: Flaws of the Web Components in 2019 and how to address them
KharkivJS: Flaws of the Web Components in 2019 and how to address them
 
INTEGRATION (HTML/CSS) The technology behind AESTHETICS
INTEGRATION (HTML/CSS) The technology behind AESTHETICSINTEGRATION (HTML/CSS) The technology behind AESTHETICS
INTEGRATION (HTML/CSS) The technology behind AESTHETICS
 
Architecting with Style
Architecting with StyleArchitecting with Style
Architecting with Style
 
.NET 1.1 Base Page Framework Article
.NET 1.1 Base Page Framework Article.NET 1.1 Base Page Framework Article
.NET 1.1 Base Page Framework Article
 
Modelling Web Performance Optimization - FFSUx
Modelling  Web Performance Optimization - FFSUxModelling  Web Performance Optimization - FFSUx
Modelling Web Performance Optimization - FFSUx
 
Best practice for magento theming by shrikant vaghela
Best practice for magento theming by shrikant vaghelaBest practice for magento theming by shrikant vaghela
Best practice for magento theming by shrikant vaghela
 
Client side performance compromises worth making
Client side performance compromises worth makingClient side performance compromises worth making
Client side performance compromises worth making
 
Structuring your CSS for maintainability: rules and guile lines to write CSS
Structuring your CSS for maintainability: rules and guile lines to write CSSStructuring your CSS for maintainability: rules and guile lines to write CSS
Structuring your CSS for maintainability: rules and guile lines to write CSS
 
CSS Methodology
CSS MethodologyCSS Methodology
CSS Methodology
 
HTML CSS & Javascript
HTML CSS & JavascriptHTML CSS & Javascript
HTML CSS & Javascript
 
Frontend Performance: Illusions & browser rendering
Frontend Performance: Illusions & browser renderingFrontend Performance: Illusions & browser rendering
Frontend Performance: Illusions & browser rendering
 
Lavacon 2014 responsive design in your hat
Lavacon 2014   responsive design in your hatLavacon 2014   responsive design in your hat
Lavacon 2014 responsive design in your hat
 

Más de jvinhit

CSS Căn bản
CSS Căn bảnCSS Căn bản
CSS Căn bảnjvinhit
 
Using The CSharp Sockets Helper Classes
Using The CSharp Sockets Helper ClassesUsing The CSharp Sockets Helper Classes
Using The CSharp Sockets Helper Classesjvinhit
 
Regular expressions quick reference
Regular expressions quick referenceRegular expressions quick reference
Regular expressions quick referencejvinhit
 
Network Programming in C#
Network Programming in C#Network Programming in C#
Network Programming in C#jvinhit
 
Xử lý ảnh
Xử lý ảnhXử lý ảnh
Xử lý ảnhjvinhit
 
Chươngii
ChươngiiChươngii
Chươngiijvinhit
 
Delegate và event trong C#
Delegate và event trong C#Delegate và event trong C#
Delegate và event trong C#jvinhit
 
Store procedure
Store procedureStore procedure
Store procedurejvinhit
 

Más de jvinhit (8)

CSS Căn bản
CSS Căn bảnCSS Căn bản
CSS Căn bản
 
Using The CSharp Sockets Helper Classes
Using The CSharp Sockets Helper ClassesUsing The CSharp Sockets Helper Classes
Using The CSharp Sockets Helper Classes
 
Regular expressions quick reference
Regular expressions quick referenceRegular expressions quick reference
Regular expressions quick reference
 
Network Programming in C#
Network Programming in C#Network Programming in C#
Network Programming in C#
 
Xử lý ảnh
Xử lý ảnhXử lý ảnh
Xử lý ảnh
 
Chươngii
ChươngiiChươngii
Chươngii
 
Delegate và event trong C#
Delegate và event trong C#Delegate và event trong C#
Delegate và event trong C#
 
Store procedure
Store procedureStore procedure
Store procedure
 

Último

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Último (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Web performance fundamental

  • 2. Why does speed matter?
  • 3. At the same time…Our applications are getting bigger.
  • 4. How web page are born ?
  • 5.
  • 6.
  • 7.
  • 8. DOM
  • 9.
  • 10. CSSOM
  • 11.
  • 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
  • 21.
  • 22.
  • 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.

Notas del editor

  1. 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.
  2. https://googlesamples.github.io/web-fundamentals/fundamentals/performance/critical-rendering-path/basic_dom.html
  3. 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.
  4. 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à rasterizing Painting 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
  5. JS change/ thuc hien tac vu update UI nao do => trigger lai qua trinh tinh toan lai layout va thay doi Layout Style 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 performance Paint: 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
  6. 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 appl Vì 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
  7. Hạn chế kích hoạt tính toán layout Dung flexbox Han che kich hoat layout som
  8. Hạn chế kích hoạt tính toán layout Việ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.
  9. 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.
  10. 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
  11. T0 and T1 captures the network and server processing times. ( speed tuy theo size of file ) Demo
  12. Tương tư như defer trong javascipt loading.
  13. 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. Demo Sử dụng media attribue để filter css Mặ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 css-import css-media font-display
  14. 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. Demo Sử dụng media attribue để filter css Mặ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
  15. 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ần Last-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ày Etag 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-store no-cache max-age Demo Text Content Minify Code, Compress Text Resource Gzip … Gzip -> vào link kéo xuống tool check
  16. https://developers.google.com/web/fundamentals/performance/rendering/optimize-javascript-execution 60 FPS => 1000/60 = 16ms de thuc hien cac tinh toan perframe Neu Để 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