Largest Contentful Paint
This document defines an API that enables monitoring the largest paint an element triggered on screen.
Status of this document
This section describes the status of this document at the time of its publication. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.
This document was published by the Web Performance Working Group as a First Public Working Draft using the Recommendation track. Publication as a First Public Working Draft does not imply endorsement by W3C and its Members.
This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.
GitHub Issues are preferred for discussion of this specification.
This document was produced by a group operating under the W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.
1. Introduction
This section is non-normative. The LargestContentfulPaint API enables developers to gain visibility into the loading and rendering process of the web pages, in order for them to be able to optimize it.
Developers today don’t have a reliable metric that correlates with their user’s visual rendering experience. Existing metrics such as First Paint and First Contentful Paint focus on initial rendering, but don’t take into account the importance of the painted content, and therefore may indicate times in which the user still does not consider the page useful.
Largest Contentful Paint (LCP) aims to be a new page-load metric that:
better correlates with user experience than the existing page-load metrics
is easy to understand and reason about
reduces the chance of gaming
The largest paint during the loading process of the page is likely to signify a meaningful event from the user’s perspective, and is therefore something we want to expose by default to developers, enabling performance teams, analytics providers and lab-based measurement tools to collect those metrics without requiring extra annotation work by the folks creating the content itself.
The API relies heavily on [ELEMENT-TIMING], which can be thought of as the low-level primitive that this high-level feature is built on top of. For cases where the content creators are willing to annotate their content and indicate the important points in the page’s loading cycle, Element Timing is the API that will provide them more control over the elements that get reported.
1.1. Elements exposed
The Largest Contentful Paint API will only expose element types that are already exposed by the Element Timing API. In this case, there is no need to annotate them with the elementtiming attribute.
1.2. Largest content
The algorithm used for this API keeps track of the content seen so far. Whenever a new largest content is found, a new entry is created for it. Content that is removed is still considered by the algorithm. In particular, if the content removed was the largest, then a new entry is created only if larger content is ever added. The algorithm terminates whenever scroll or input events occur, since those are likely to introduce new content into the website.
1.3. Usage example
The following example shows an image and a large body of text. The developer then registers an observer that gets candidate entries for the largest paint while the page is loading.
1.4. Limitations
The LargestContentfulPaint API is based on heuristics. As such, it is error prone. It has the following problems:
The algorithm halts when it detects certain types of user inputs. However, this means that the algorithm will not capture the main content if the user input occurs before the main content is displayed. In fact, the algorithm may produce meaningless results or no results at all if user input occurs very early.
To account for image carousels, content is still considered as the largest even if it’s removed. This presents problems for websites with splash screens that use large content as placeholders.
2. Largest Contentful Paint
Largest Contentful Paint involves the following new interface:
2.1. LargestContentfulPaint interface
Each LargestContentfulPaint object has these associated concepts:
A , initially set to 0.
A , initially set to 0.
A , initially set to 0.
An , initially set to the empty string.
A , initially set to the empty string.
An containing the associated Element , initially set to null .
The entryType attribute’s getter must return the DOMString «largest-contentful-paint» .
The name attribute’s getter must return the empty string.
The startTime attribute’s getter must return the value of this’s renderTime if it is not 0, and the value of this’s loadTime otherwise.
The duration attribute’s getter must return 0.
The renderTime attribute must return the value of this’s renderTime.
The loadTime attribute must return the value of this’s loadTime.
The size attribute must return the value of this’s size.
The id attribute must return the value of this’s id.
The url attribute must return the value of this’s url.
The element attribute’s getter must return the value returned by running the get an element algorithm with element and null as inputs.
Note: The above algorithm defines that an element that is no longer descendant of the Document will no longer be returned by element ‘s attribute getter, including elements that are inside a shadow DOM.
This specification also extends Document by adding to it a concept, initially set to 0. It also adds an associated , which is initially an empty set. The content set will be filled with ( Element , Request ) tuples. This is used for performance, to enable the algorithm to only consider each content once.
Note: The user agent needs to maintain the content set so that removed content does not introduce memory leaks. In particular, it can tie the lifetime of the tuples to weak pointers to the Elements so that it can be cleaned up sometime after the Elements are removed. Since the set is not exposed to web developers, this does not expose garbage collection timing.
3. Processing model
3.1. Potentially add LargestContentfulPaint entry
Note: A user agent implementing the Largest Contentful Paint API would need to include «largest-contentful-paint» in supportedEntryTypes for Window contexts. This allows developers to detect support for the API.
In order to , the user agent must run the following steps:
renderTime , a DOMHighResTimestamp
loadTime , a DOMHighResTimestamp
Let contentIdentifier be the tuple ( element , imageRequest ).
If document ’s content set contains contentIdentifier , return.
Append contentIdentifier to document ’s content set
Let url be the empty string.
If imageRequest is not null, set url to be imageRequest ’s request URL.
Let id be element ’s element id.
Let width be intersectionRect ’s width .
Let height be intersectionRect ’s height .
Let size be width * height .
Let rootWidth be root ’s viewport’s width, excluding any scrollbars.
Let rootHeight be root ’s viewport’s height, excluding any scrollbars.
If size is equal to rootWidth times rootHeight , return.
If imageRequest is not null, run the following steps:
Let naturalWidth and naturalHeight be the outputs of running the same steps for an img ‘s naturalWidth and naturalHeight attribute getters, but using imageRequest as the image.
Let naturalSize be naturalWidth * naturalHeight .
Let displayWidth and displayHeight be the outputs of running the same steps for an img ‘s width and height attribute getters, but using imageRequest as the image.
Let displaySize be displayWidth * displayHeight .
Let penaltyFactor be min ( displaySize , naturalSize ) / displaySize .
Multiply size by penaltyFactor .
If size is less than or equal to document ’s largest contentful paint size, return.
Let contentInfo be a map with contentInfo [«size»] = size , contentInfo [«url»] = url , contentInfo [«id»] = id , contentInfo [«renderTime»] = renderTime , contentInfo [«loadTime»] = loadTime , and contentInfo[«element»] = element .
Create a LargestContentfulPaint entry with contentInfo , and document as inputs.
3.2. Create a LargestContentfulPaint entry
In order to , the user agent must run the following steps:
Set document ’s largest contentful paint size to contentInfo [«size»].
Let entry be a new LargestContentfulPaint entry with document ’s relevant realm, with its
size set to contentInfo [«size»],
url set to contentInfo [«url»],
id set to contentInfo [«id»],
renderTime set to contentInfo [«renderTime»],
loadTime set to contentInfo [«loadTime»],
and element set to contentInfo [«element»].
3.3. Modifications to the DOM specification
This section will be removed once the [DOM] specification has been modified.
Right after step 1, we add the following step:
If target ’s relevant global object is a Window object, event ’s type is scroll and its isTrusted is false, set target ’s relevant global object’s has dispatched scroll event to true.
3.4. Modifications to the HTML specification
Each Window has , a boolean which is initially set to false.
4. Security & privacy considerations
This API relies on Element Timing for its underlying primitives. LCP may expose some element not exposed by Element Timing in case that they are smaller than Element Timing’s limits, but are still the largest elements to be painted up until that point in the page’s loading. That does not seem to expose any sensitive information beyond what Element Timing already enables.
Conformance
Document conventions
Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.
All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]
Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class = «example» , like this:
This is an example of an informative example.
Informative notes begin with the word “Note” and are set apart from the normative text with class = «note» , like this:
Note, this is an informative note.
Conformant Algorithms
Requirements phrased in the imperative as part of algorithms (such as «strip any leading space characters» or «return false and abort these steps») are to be interpreted with the meaning of the key word («must», «should», «may», etc) used in introducing the algorithm.
Conformance requirements phrased as algorithms or specific steps can be implemented in any manner, so long as the end result is equivalent. In particular, the algorithms defined in this specification are intended to be easy to understand and are not intended to be performant. Implementers are encouraged to optimize.
Largest Contentful Paint (LCP): What It Is and 11 Ways to Improve It
Understanding Core Web Vitals helps ensure your website can offer the best user experience. They consist of multiple metrics representing how users interact with your website, one of which is the largest contentful paint (LCP).
In this article, we will dive deeper into the largest contentful paint by looking at how to measure it and some helpful methods to improve it.

What Is the Largest Contentful Paint?
The largest contentful paint (LCP) represents a website’s loading time. It focuses on measuring how fast the web page renders its largest elements, including images and text blocks. A good LCP score can indicate a better user experience and lower bounce rates.
How to Measure the Largest Contentful Paint
Measuring the Core Web Vitals metrics, from first input delay (FID) to largest contentful paint (LCP), requires certain tools and software. Field data is gathered from real users and their experiences, while lab data collects information from a simulated environment. Some tools also combine both data types to provide a more detailed report to optimize your website.
One of the most popular tools to measure the LCP is Google’s PageSpeed Insights. It is a free tool that helps users analyze and diagnose web performance by presenting relevant audits and improvement opportunities.
Using PageSpeed Insights is relatively easy. Here is what you need to do when operating this tool:
- Type or paste the site URL into the search bar at the top of the page, and click on the Analyze button. Note that completing the performance analysis might take a few minutes.
- Once the analysis is complete, check the Diagnose performance issues section to get useful metrics and recommendations to improve performance. A score represents the overall result.
- You can find more metrics, including the largest contentful paint, first contentful paint, and cumulative layout shift. Click on Expand view to read brief explanations of each metric.
- PageSpeed Insights also gives you multiple recommendations and diagnostics to improve the site’s performance. It is also possible to filter them based on relevant Core Web Vitals.
Other tools you might want to consider are Lighthouse and SearchConsole.
What Is a Good Score for the Largest Contentful Paint?

The largest contentful paint score is measured in seconds. As a rule of thumb, a web page should be able to render its largest elements in under 2.5 seconds.
A web page with an LCP score of 1.2 seconds or less means it is good enough and you don’t have to take any further actions. A score between 1.2 and 2.5 seconds is still acceptable. However, you might want to adjust some elements to improve it.
An LCP score higher than 2.5 seconds means your site has poor performance that may negatively impact user experience and ultimately hinder your site’s growth.
What Elements Does the Largest Contentful Paint Measure?
Each metric measures different website elements. For example, the first contentful paint (FCP) measures the time needed for a web page to display the first content. In this case, content includes images, charts, and text elements.
Meanwhile, the LCP only measures how fast a page can load the largest element within the viewport, which is the area of the window that shows content. This is because the time needed to display the largest element is a major indicator of how fast the page can load.
Elements that trigger LCP entries include:
- Image elements (including ones inside an SVG element)
- Video elements
- Elements with a background image loaded using the url() function
- Text nodes within block-level elements
What is considered the largest element depends on the type. For image elements, the reported size is either its visible size or its intrinsic size, whichever is the smallest. For text elements, LCP only considers their text nodes’ size.
Additionally, the largest contentful paint won’t consider any parts of an element that extends or clips outside of the viewport. This means that the size calculation does not include any margin, padding, or border.
How to Improve the Largest Contentful Paint: 11 Effective Methods
Since the largest contentful paint is a major indicator of a site’s page load speed, a poor LCP score can result in a poor user experience. There are several common causes of bad website performance, including:
- Slow server response times and resource load times
- Client-side rendering
- Render-blocking resources
Fortunately, there are several ways to solve these issues. Let’s look at 11 effective methods to improve your site’s largest contentful paint score.
1. Utilize a CDN
Difficulty level: medium
Impact: low/medium/high
A content delivery network (CDN) is a great tool to improve your site’s traffic management. A CDN uses additional servers to assist when the origin server needs to handle high traffic. Usually, larger sites use this technology to handle many visitors regularly.
Because of that, a CDN can help improve the LCP by balancing network load since visitors’ requests don’t need to queue in the same server. This may result in a faster LCP score and potentially improve user experience.
A CDN can also be enhanced with additional software like an image CDN that optimizes and transforms image sizes in real-time. This can further improve how fast a media-rich website renders its content.

The process of setting up a CDN varies depending on your hosting provider. Usually, it is relatively simple. If you are using Hostinger, it is possible to enable a CDN directly from hPanel.
One of the most popular CDN solutions is Cloudflare, offering more than 120 centers worldwide. This service provides a free plan and has a simple configuration process, especially if you are configuring Cloudflare on WordPress.
You might want to consider other CDN solutions, including StackPath, Sucuri, and Google Cloud CDN.
2. Ensure Right Image Sizing
Difficulty level: easy
Efficiency: low/medium/high
As mentioned before, some images might constitute a large contentful paint element depending on their sizes. Therefore, ensuring your web pages have the optimized image size is important to maintain a good LCP score.
The key here is to understand the right image sizing based on the user’s device. To ensure a good LCP score, web pages need to use responsive images.
For example, if the desktop version of your site uses large-sized pictures, the mobile version should use medium-sized images.
It is also important to know your website platform’s default image sizes. For example, there are four default WordPress image sizes, which are:
- Thumbnail – precisely 150 pixels square.
- Medium – up to 300 pixels square.
- Large – maximum 1024 pixels square.
- Full size – refers to the original image size.
Keep in mind that images report their smallest element size. This means a compressed image will report its visible size, while an enlarged image will report its original size.
3. Optimize Images
Difficulty level: easy
Efficiency: low/medium/high
Aside from ensuring the right sizing, there are other ways to optimize images on your site to improve loading time.
If you’re optimizing images in WordPress, the method is relatively easy as you’ll only need to choose the right file format or use a plugin.
Some of the most popular tools to optimize images for websites include TinyPNG, Imagify, and Kraken. Plugins like Optimole, EWWW Image Optimizer, and ShortPixel are also great options for WordPress users.

Optimizing images is not only useful to improve LCP score. It allows you to save storage space and potentially improve your site’s search engine optimization (SEO) performance. If you’re a WordPress user, check out more ways to improve your SEO.
Suggested Reading
Images are not the only element you need to optimize to improve your WordPress site’s performance. Read how to speed up WordPress to find out more.
4. Improve Server Response Time
Difficulty level: medium
Efficiency: low/medium/high
Your page load time is tightly related to the web server response times. The back and forth process between a user’s browser request and the server request is one of the main factors affecting loading speed. This process is also known as the round trip time (RTT).
There are several ways you can improve server response time, including:
- Implement server-side caching – web owners can leverage browser and server-side caching. The server-side caching feature is typically available on your hosting configuration.
- Upgrading server specifications – a server’s hardware specifications significantly affect its performance. Therefore, consider upgrading to a server with better CPU capabilities and larger storage capacity.
- Optimize application codes – streamlining codes used on functions as a database query can help improve an LCP score. For example, removing non-critical CSS can help speed-up initial rendering. Don’t hesitate to ask for assistance from web developers since this step can be very technical.
For WordPress websites, plugins like WP-DBManager can help optimize your database by reducing bloats and scheduling automatic cleanups.
5. Use a Reliable Web Hosting Provider
Difficulty level: easy
Efficiency: high
The quality of web hosting is a major factor affecting the overall web performance. Good hosting is typically configured to enhance user experience and comes with various features to make web management easier.
Therefore, choosing a web hosting plan that fits your site’s specifications can improve the perceived load speed. Hostinger has a wide range of hosting options that cater to various needs and preferences.
For example, our WordPress hosting plans are specifically fine-tuned to optimize the CMS’s capabilities and ensure faster loading time. The provider also uses an intuitive control panel that makes your web management experience less of a hassle.
6. Implement Caching
Difficulty level: easy/medium/hard
Efficiency: low/medium/high
Caching refers to storing static assets of a page in temporary storage. This allows for faster page load time by reducing the amount of data transferred during the initial rendering process. There are two main caching methods – server-side caching and browser caching.
By leveraging browser caching, visitors can store cache in their local storage. As a result, they don’t have to download the same data when revisiting your site. You can enable browser caching either manually or using plugins.
On the other hand, server-side caching is a method of storing a pre-made version of a web page in the origin server. With this method, the server doesn’t have to reconstruct or load page content from the database when a user revisits the site.

One of the most popular tools to enable website caching is LiteSpeed. It comes with advanced caching functionality and other useful features like dynamic content optimization and an HTTP load balancer.
7. Fix Lazy Loading Issues
Difficulty level: medium
Efficiency: low/medium/high
Lazy loading is a technique where a page defers non-critical CSS and other resources during the initial rendering. Instead, it will focus on loading above-the-fold content and render non-critical resources only when needed to make the page load process faster.
With this method, your site can load files asynchronously depending on their distance to the viewport.
For example, content rendered above the fold like a featured image will appear immediately during the initial loading. However, elements like video thumbnails outside of the viewport are replaced by placeholder images until users scroll through them.
However, lazy loading can sometimes worsen the LCP score due to several issues. For instance, websites that implement native lazy loading and have all of their images follow the lazy loading behavior might get a lower LCP score.
To fix this issue, simply tag the hero or featured image that potentially gets selected as the largest contentful paint element with the attribute loading=”eager”. This function allows the image element to render immediately regardless of its distance from the viewport.
This can also happen to lazy loading methods using JavaScript. Since the browser needs to execute the JavaScript before rendering an element, it might prolong the loading time and worsen the LCP score.
The most effective solution to this problem is to disable lazy loading on images rendered above the fold. As a result, browsers will load them without having to execute JavaScript beforehand.
8. Minify JS, CSS, and HTML Files
Difficulty level: easy
Efficiency: low
Minification is a method to decrease file size mainly by reducing lines of code within the file. This is one of the most common file optimization methods that can help improve your LCP metric.
Some of the core files like CSS, JavaScript, and HTML may contain many unnecessary white spaces within the code that make their size larger. Even though they might not seem significant individually, they can worsen site performance when accumulated.
Web owners can minify CSS, HTML, and JS files manually or using WordPress plugins. Some of the most popular minifying plugins include Fast Velocity Minify and WordPress Super Minify.

After doing so, don’t forget to check the Core Web Vitals report. Tools like PageSpeed Insights can give you other minification opportunities in case you missed some.
9. Eliminate Render-Blocking JavaScript and CSS
Difficulty level: easy
Efficiency: low/medium/high
Render-blocking resources are parts of files that may slow down the page loading process. This can typically be found in CSS and JS files. These resources might cause elements in the page to load longer at the same time, giving the impression of poor website performance.
Because of that, eliminating render-blocking CSS and JavaScript should be one of your priorities to get a better Core Web Vitals report. This allows you to implement progressive loading, which may help reduce bounce rate.
Some WordPress plugins can help you eliminate render-blocking resources more efficiently. These include W3 Total Cache, Autoptimize, and Speed Booster Pack.

Remember to also check suggestions from your lab tools on which non-critical CSS or JS files you should eliminate.
10. Compress Text Resources
Difficulty level: easy/medium/hard
Efficiency: high
Aside from minification, compressing can be a good method to optimize text resources like CSS, HTML, and JavaScript. This can make the transfer process faster due to the smaller file size, resulting in a better LCP score.
One of the most common methods of text resource compression is GZIP which falls into the lossless compression category. This means it will keep all the information within the file during the compression process.
Web owners can enable GZIP compression using WordPress plugins like WP Rocket or free online compression services like gzip.swimburger.net. Keep in mind that some web hosting companies also enable GZIP by default.
11. Defer Parsing of JavaScript
Difficulty Level: easy/medium/hard
Efficiency: high
A web browser typically loads codes from top to bottom but will prioritize any JavaScript before continuing. This may slow down the page load speed and worsen the user experience.
Defer parsing of JavaScript means adjusting the page to delay processing any non-critical JavaScript code on the page. With this method, the browser can prioritize loading the actual page content faster and maintain visitors’ attention.

You can defer parsing JavaScript on your page manually by modifying the function.php file or using tools like Speed Booster Pack or WP Rocket.
Conclusion
The largest contentful paint (LCP) is one of the Core Web Vitals metrics that represents how fast a web page can load its largest content. This is a major user-centric metric that affects the load speed and overall user experience.
In this article, we have learned how to measure the LCP score and 11 ways to improve it, namely:
- Utilize content delivery network
- Ensure the right image sizing
- Optimize images
- Improve server response time
- Choose a reliable web hosting provider
- Implement caching
- Fix lazy loading issues
- Minify CSS, HTML, and JavaScript
- Eliminate render-blocking resources
- Compress text resources
- Defer parsing of JavaScript
Hopefully, this article has helped you improve your largest contentful paint score. If you have any additional tips or questions regarding this topic, leave a comment below.
LCP: как улучшить и оптимизировать

Поисковые системы постоянно совершенствуют алгоритмы ранжирования, чтобы на верхних строчках выдачи попадали качественные сайты, которые обеспечивают идеальный пользовательский опыт. Юзеры должны найти ответ на свой вопрос, а не пробираться к нему через тонну рекламных объявлений.
Автоматизированные алгоритмы постоянно следят за тем, чтобы пользователи оставались довольны. Для этих целей придумали поведенческие факторы — метрики, позволяющие измерить качество user experience. Если контент просто заточен под ключи и не имеет ценности, ПФ это покажут.
Если хотите создавать инфосайты под контекстную рекламу или собираетесь монетизировать их партнёрками и рассчитываете на бесплатный трафик, придётся адаптировать проекты под новые алгоритмы. Сегодня Monstro расскажет об одном из ключевых факторов, который влияет на эффективность продвижения в любых нишах.
Что такое показатель Largest Contentful Paint (LCP)?
Конкуренция в поисковой выдаче постоянно растёт потому что появляется всё больше качественных сайтов. В 2021 году контента, раскрывающего пользовательский интент уже мало, чтобы находиться в ТОПе годами. Сайт должен быть быстрым, удобным и предлагать дополнительные инструменты, которых нет у других игроков ниши.
В плане совершенствования формулы ранжирования Google ушёл далеко вперед от Яндекса. Пока в Яндексе работают над нейросетями, которые генерируют контент, Гугл вводит в действие новые алгоритмы и делает всё, чтобы информационные и коммерческие проекты подстраивались под новую реальность.
Google анонсировал Core Web Vitals ещё в прошлом году, но отметил, что новый фактор ранжирования начнёт учитываться основным алгоритмом только в 2021 году. Развёртывание запланировали на май и отметили, что у вебмастеров ещё куча времени, чтобы пофиксить проблемы.
Подстраиваться под изменения или нет — каждый решает сам. Понятно, что новый алгоритм не поменяет выдачу в один момент, но изменения однозначно будут. Ещё больший сдвиг в сторону качества сайта говорит о том, что Google любит не только ссылки, а заботится об аудитории.
Если на проекте много рекламы, которая грузится по 10-15 секунд и перекрывает основной контент, в процессе измерения новых метрик это будет видно и сайт может потерять позиции. Такие проекты не должны попадать в ТОП и хорошо ранжироваться. Особенно если рядом есть чистые сайты с хорошим контентом и высокой скоростью загрузки.
В состав Core Web Vitals («Основных интернет-показателей») входят 3 метрики, каждая из которых отвечает за свои задачи. В совокупности они помогают оценить, насколько быстро сайт загружает контент и как скоро он становится доступен для пользователей. Если значения для метрик из CWV будут слишком маленькими, сайт может вылететь из ТОПа.
Одной из метрик является Largest Contentful Paint (LCP). Параметр измеряет скорость загрузки, а точнее момент, когда загружается основной контент на странице. К примеру, если в хедере стоит рекламный блок и он грузится 5-10 секунд, сайт не пройдет проверку по LCP.
Largest Contentful Paint отражает время, в течение которого на странице загружается самый тяжелый блок. Это может быть картинка, видео, содержание или что-то другое. Всё зависит от структуры шаблона и особенностей проекта.
Обычно у вебмастеров, которые далеки от технических терминов, возникают проблемы с пониманием сущности Core Web Vitals, хотя ничего сложного в этом нет. Основные интернет-показатели Google не придумали на пустом месте, метрики существовали давно.
Гугл просто объединил их в единую систему, а затем призвал вебмастеров провести комплексную оценку значения метрик и внести изменения в технические параметры, чтобы обеспечить более качественный пользовательский опыт. Те, кто не будут ничего менять, останутся за бортом.
Самый крупный элемент на странице одновременно является самым важным, поэтому вопросы как улучшить LCP уже давно не являются чисто теоретическими. Многие владельцы сайтов, приносящих доход, внесли изменения и рассчитывают на сохранение трафика после введения нового фактора ранжирования в действие.
Раньше Google фокусировал внимание на First Contentful Paint, но позже решил, что важно не просто отследить скорость загрузки первого контента, а измерить время, за которое подгружается самый тяжелый блок на странице. Эта метрика более понятна для вебмастеров и провести замер в режиме реального времени может каждый пользователь.
В Гугле прекрасно понимают, что при загрузке страницы контент может меняться. Например, рекламные объявления часто скачут туда-сюда потому что CSS срабатывает не сразу или возникают неполадки при загрузке скриптов. Поэтому при появлении новых больших элементов браузер отправляет анализаторам данные о LCP и надо ориентироваться на время работы последнего события.
Размер самого большого элемента на странице зависит от особенностей сайта. К примеру, в веб-версии Инстаграма LCP учитывает время загрузки логотипа, который появляется ещё до загрузки основного контента. Он становится доступен быстрее других блоков и «ждёт» когда появится форма входа и другие элементы.
Ещё одна распространённая ситуация подразумевает смещение приоритета. К примеру, в ходе загрузки самым большим элементом была картинка, а потом им стал текст, оформленный в виде цитаты. Анализаторы, которые считывают LCP, без проблем определяют самый большой элемент и фиксируют время его загрузки.
Необязательно разбираться в технических деталях, чтобы понять суть LCP и других метрик. Надо вникнуть в базовые особенности и потратить время на оптимизацию проекта, если рассчитываете на успешное продвижение в поисковой системе.
Почему метрика так важна?
Google ранее анонсировал, что с мая 2021 года фактор Page Experience станет частью основного алгоритма ранжирования, а Core Web Vitals войдут в его состав. Поэтому если сайт не проходит проверку по LCP и двум другим метрикам, со временем его видимость может упасть.
Пока нет никаких подтверждений того, что новый фактор ранжирования полностью изменил ситуацию в поисковой выдаче, но это может произойти в любой момент. И если вебмастер хочет и дальше зарабатывать на бесплатном трафике, надо подстроиться под новую реальность.
FID и CLS, входящие в состав «Основных интернет-показателей», тоже важны, но только в комплексе. Если оптимизировали одну метрику и рассчитываете на заметный результат, его может и не быть. Важно провести комплексную работу и постоянно мониторить ситуацию.
Метрика LCP важна потому что она:
- Учитывает самый большой блок на странице, на который браузер пользователя тратит больше всего ресурсов.
- Может влиять на индексацию ресурса. Google любит «выплёвывать» страницы с некачественным контентом, которые плохо раскрывают интент.
- Тесно связана с конверсией страницы и сайта. Мало кто будет оформлять заказ на проекте, который грузится несколько минут или зависает из-за высокой нагрузки.
- Позволяет определить качество ресурса. Если самым большим блоком будет реклама на всю высоту экрана браузера, LCP это покажет.
- Даёт понять юзеру, что контент на странице загружается и не надо закрывать вкладку браузера.
FID и CLS тоже важны в контексте пользовательского опыта, но можно сказать, что LCP на первом месте. Юзеры не любят долго ждать загрузки контента и могут покинуть страницу пока прогружается самый объемный блок. Поэтому надо постараться по максимуму оптимизировать значение метрики.
Как измерить показатель LCP?
Первая проблема, которая возникает у многих вебмастеров, касается не улучшения показателя LCP, а его проверки. Мало кто знает, как проводить тесты в режиме реального времени. Core Web Vitals уже давно есть в Google Search Console, но данные там обновляются с большой задержкой.
В отчете по скорости загрузки проекта в PageSpeed Insights чётко написано, что «Согласно данным наблюдений за последние 28 дней эта страница не отвечает требованиям к основным интернет-показателям». То есть алгоритмы анализируют значения метрик примерно в течение месяца.
К примеру, если вебмастер провёл масштабную работу по оптимизации и рассчитывает, что цифры мгновенно станут зелёными, его надежды не оправдаются. Обновление не происходит мгновенно и в некоторых случаях может затянуться надолго.
Если хотите проверить актуальное состояние Core Web Vitals, ориентироваться на данные из консоли для вебмастеров или цифры PageSpeed Insights не стоит. Ознакомиться с ними можно, но фактическое значение метрик может быть совсем другим.
Лучше проводить замеры в режиме реального времени, чтобы получить актуальные значения и зря не рассчитывать на преимущества от оптимизации. Не все знают, как это сделать, поэтому важно рассказать об инструментарии вебмастеров.
В Google уже давно уверены в том, что Core Web Vitals критически важны для оценки качества пользовательского опыта, поэтому инструменты для проверки значения метрик есть почти в каждом релевантном сервисе поисковой системы.
Есть несколько инструментов для замера LCP:
-
. В отчете собраны анонимизированные данные пользователей с замером метрик. Ручные замеры делать не нужно потому что все цифры уже есть в отчёте. Данные из отчёта поступают в консоль для вебмастеров и PageSpeed. . Панель для разработчика в браузере позволяет выполнять замеры на стороне клиента. Инструмент можно использовать для быстрого получения значения метрик. . На Гитхабе есть небольшая библиотека, которая позволяет быстро сделать замеры. На странице проекта доступна полная документация по работе с API. . Сервис загружает страницу в режиме эмуляции и не учитывает реальную ситуацию на устройстве пользователя. Поэтому ориентироваться на данные не стоит.
Учитывайте, что скорость загрузки сайта зависит от большого количества факторов. На конечные значения влияет скорость интернета, фоновая активность на устройстве и особенности поведения юзера. Поэтому замеры в режиме реального времени дадут чёткую картину и позволят сформировать комплексный отчёт.
Если по итогам замеров с разных устройств будет видно, что показатели Core Web Vitals очень плохие, надо срочно внедрять правки и подгонять метрики до входа в «зелёную зону». Иначе не стоит рассчитывать на высокие позиции.
Тем, кто не хочет разбираться в JS, API и других сложных инструментах, идеально подойдет консоль для разработчиков в браузере. Вот пошаговая инструкция по запуску теста Core Web Vitals:
- Откройте консоль разработчика в браузере.
- Переключитесь во вкладку Performance.
- Активируйте галочку Web Vitals.
- Нажмите иконку со стрелочкой и надписью Start profiling and reload page.
- Дождитесь окончания замеров и ознакомьтесь с данными.
На скриншоте ниже видно, что с LCP у проекта всё хорошо и FCP тоже в порядке. Но стоит провести дополнительные замеры с разных устройств, чтобы увидеть картину целиком и расслабиться, если всё в порядке.
Для замеров Core Web Vitals есть крутое расширение под Google Chrome, которое написано на основе библиотеки CWV. После запуска измерений данные считываются в режиме реального времени и отображаются в браузере практически мгновенно.
Установите его, откройте доступ к данным и нажмите на иконку в адресной строке. Ознакомьтесь с данными и заюзайте несколько дополнительных инструментов. Расширение показывает, что на VC.ru всё отлично с «Основными интернет-показателями», а у PageSpeed Insights противоположное мнение.
Дополнительно можно использовать GTmetrix и WebPage Test. Эти инструменты будут полезны вебмастерам и откроют более быстрый доступ к замерам метрик Core Web Vitals. Чтобы получить комплексные данные, используйте несколько тулзов одновременно.
Эффективные способы улучшения показателя LCP
Когда вебмастера видят, что их проекты не проходят проверку CWV, у них возникает задача оптимизировать показатель LCP. На этом моменте многие начинают судорожно искать плагины и сервисы, которые улучшают показатели в один клик.
Важно понять, что Core Web Vitals учитывают комплексные метрики. Нельзя просто минифицировать CSS и получить 100 баллов в PageSpeed Insights. Аналогичная ситуация и с LCP.
Чтобы разобраться с улучшением значения метрики, необходимо чётко понимать, что влияет на Largest Contentful Paint. Это поможет сформировать пошаговый план действий и последовательно выполнить все действия.
Отрисовка самого большого контента на странице должна происходить быстрее чем за 2,5 секунды. Всё, что дольше — проваленный тест Core Web Vitals и потенциальный риск для позиций в органической выдаче.
На LCP влияет несколько факторов:
- Время ответа сервера. Чем быстрее сайт откликнулся на запрос браузера пользователя, тем лучше.
- JavaScript и CSS с блокировкой рендеринга. Некоторые элементы на странице могут блокировать её отображение и пользователю приходится ждать загрузки. В идеальном состоянии блокирующих элементов не должно быть.
- Время загрузки ресурса. В 2021 году мало кто будет ждать загрузку контента несколько минут.
- Рендеринг на стороне клиента. Рендеринг в браузере с помощью Javascript, данные обрабатываются на устройстве пользователя.
Для оптимизации LCP надо понять, какой блок на странице является самым крупным и увидеть, насколько быстро он грузится. Время ответа сервера зависит от качества оптимизации на стороне хостинг-провайдера. Лучше выбирать хостинги, которые по умолчанию выдают хорошие показатели.
Для повышения скорости загрузки страницы можно использовать GZIP, CDN, а также технологии кэширования. Если речь идёт о сайте на базе WordPress, то вебмастерам доступны десятки плагинов для настройки кэша.
- Оптимизируйте медиаконтент. Картинки лучше по максимуму сжать и конвертировать в формат WebP.
- Отложите загрузку второстепенных ресурсов. Асинхронная загрузка JS здорово помогает ускорить сайт.
- Сократите объем JS. Удалите все неиспользуемые скрипты, минифицируйте оставшиеся и объедините их в один файл.
- Используйте предварительный рендеринг. Он помогает защититься от перезагрузки сервера.
- Устраните элементы, блокирующие рендеринг. Данные о наличии таких блоков есть в отчёте PageSpeed Insights.
- Используйте критический CSS. Он помогает встроить главные стили в список ресурсов для приоритетной загрузки, а остальные правила отложить до момента взаимодействия пользователя с элементами.
Оптимизировать показатель LCP вручную без опыта и знаний очень сложно. Поэтому у типичного вебмастера есть два варианта — разобраться самостоятельно или заплатить программисту. Второй подход более комфортный потому что каждый сможет заняться своими задачами.
Ещё один выход из ситуации — покупка оптимизированных тем. Большое количество шаблонов на Themeforest и других маркетплейсах по умолчанию хорошо спроектированы. Остаётся соблюдать простые правила, чтобы сайт прошёл проверку Core Web Vitals и набрал хорошие баллы.
Если будете сотрудничать с прогером, не забывайте использовать инструменты для замера в режиме реального времени. И не ведитесь на предложения специалистов получить 100 баллов в PageSpeed. Обман алгоритмов не приведёт не даст ничего хорошего.
Время загрузки самого большого контента не должно превышать 2,5 секунд.
Есть, но автоматизировать задачу очень сложно. Только если речь идёт о простой HTML-странице без админки. И даже в этом случае выйти на хорошие показатели без ручной настройки практически невозможно.
Да, если хотите получать бесплатный трафик из Google.
Раз в месяц, задержка может быть и больше. Ориентируйтесь на данные замеров в real-time.
Совмещайте несколько сервисов из нашей статьи. Например, расширение для Chrome и GTmetrix или WebPage Test.
Как измеряются метрики сайта: LCP, FID и CLS
5 мая 2020 года Google представили Web Vitals — важные метрики сайтов которые позволяют измерить удовлетворенность пользователей и влияют на SEO. В этой статье мы расскажем что это за показатели и как они измеряются.
Основные метрики сайтов
LCP — Largest Contentful Paint
Это время отрисовки самой большой и видимой части содержимого на первом экране вашего сайта. Это может быть картинка, видео или текст (подробнее в блоге Google). Для хорошего пользовательского опыта значение LCP не должно превышать 2,5 секунды.

FCP — First Contentful Paint (Первая отрисовка контента)
Как измерить LCP?
LCP в реальных условиях можно измерить с помощью этих инструментов:
Для лабораторных измерений используют следующие инструменты:
Чтобы измерить LCP с помощью JS и Largest Contentful Paint API, можно использовать следующий код:
В приведенном выше примере, каждое событие largest-contentful-paint представляет текущего кандидата на роль LCP. В общем случае, значение startTime для последнего события является значением LCP, однако это не всегда так. Не все события подходят для измерения LCP.
Результаты работы API и то, как на самом деле рассчитывается метрика сайта, отличаются:
- API будет выдавать результат для страниц, загруженных на фоновой вкладке, но при расчете LCP эти страницы следует игнорировать;
- API будет продолжать отправлять результаты после того, как страница перешла в фон, но эти записи следует игнорировать (элементы могут рассматриваться только в том случае, если страница все время находилась на переднем плане);
- API не сообщает результаты при восстановлении страницы из кэша при переходе вперед\назад в браузере, но LCP следует измерять в этих случаях, поскольку пользователи воспринимают их как отдельные посещения страниц;
- API не учитывает элементы внутри iframes, но для правильного измерения LCP вы должны учитывать их. Подфреймы могут использовать API, чтобы сообщить о своих LCP родительскому фрейму для агрегирования.
Чтобы не вдаваться в эти подробности можно использовать web-vitals JavaScript библиотеку, которая сделает всё за вас:
Что если самый большой элемент на экране не является самым важным?
В таком случае, для измерения времени загрузки других элементов можно использовать Element Timing API.
FID — First Input Delay
FID — это время через которое пользователь может начать взаимодействовать с сайтом. Значение не должно превышать 100 миллисекунд. В новом PageSpeed этот параметр заменят на TBT (Total Blocking Time), который вычисляет блокировку содержимого сайта.
Как измерить FID?
FID — это метрика сайта, которую можно измерить только в реальных условиях, так как она требует наличия реального пользователя, взаимодействующего с вашей страницей. Вы можете измерить FID с помощью следующих инструментов:
Метрика общего времени блокировки (TBT) измеряется в лабораторных условиях, хорошо коррелирует с FID в реальных условиях, а также фиксирует проблемы, влияющие на интерактивность. Оптимизация, улучшающая TBT в лаборатории, также должна улучшить FID для пользователей.
Чтобы измерить FID можно использовать Event Timing API. Вот примерный код на JS:
В приведенном выше примере, для каждого события first-input задержка вычисляется как разница между startTime и processingStart . Но для этого, как и в случае с LCP, подходят не все события.
Список различный между работой API и реальной метрикой, похож на список для LCP. Поэтому и здесь лучше использовать web-vitals JavaScript library.
CLS — Cumulative Layout Shift
CLS измеряет степень стабильности контента на вашем сайте. Значение будет увеличиваться от элементов сайта (картинок, рекламных блоков и тд.) которые загружаются позже и вызывают смещение контента. Подробнее о CLS в нашем переводе — «Что такое CLS сайта и почему он важен».
Как измерить CLS?
CLS можно измерить синтетически (в лаборатории) или для реальных пользователей (через RUM). Лабораторные измерения могут фиксировать только изменения вёрстки при однократной или многократной загрузке страницы, в то время как измерения RUM будут в большей степени отражать то, что видят реальные пользователи, когда они взаимодействуют с сайтом.
Величина совокупного сдвига вёрстки — это сумма влияния всех неожиданных сдвигов вёрстки, которые происходят с пользователем в течение определенного периода времени. Считаются только сдвиги контента, который виден на экране. Всё, что находится за пределами экрана, не влияет на пользователя. Чтобы рассчитать балл CLS по каждому сдвигу вёрстки, нам нужно рассмотреть две составляющие этого сдвига: его долю воздействия и долю расстояния.
Доля воздействия измеряет, насколько сильно экран изменился от одного кадра (момента) к следующему. Доля расстояния измеряет наибольшее расстояние, пройденное любым из этих нестабильных элементов на экране.
Обычно измерение производится до вызова браузером события onload.
CLS поддерживается множеством JS библиотек для измерения метрик сайта, например boomerang.js и perfume.js.
CLS в полевых условиях можно измерить с помощью апи для браузера — Layout Instability API .
Это экспериментальное API сообщает об отдельных вхождениях layout-shift любому PerformanceObserver , зарегистрированному на странице.
Каждое вхождение layout-shift это событие, которое происходит, когда элемент меняет своё положение между двумя кадрами. Элемент, просто изменивший свой размер или впервые добавленный в DOM, не обязательно вызовет сдвиг разметки, если он не повлияет на другие видимые элементы DOM.
Сдвиг разметки это не всегда плохо. Например если пользователь нажимает на кнопку на одностраничном сайте, это может быть ожидаемым поведением. Каждое событие layout-shift имеет флаг hadRecentInput, сообщающий, был ли ввод от пользователя за 500мс от сдвига. Если это так, то этот сдвиг разметки, вероятно, можно исключить из CLS.
hadRecentInput становится true после событий: mousedown , keydown ,и pointerdown .
Открытых библиотек для измерения CLS множество, например, Boomerang или web-vitals.
Если вы хотите поэкспериментировать с необработанными сдвигами разметки через Layout Instability API , то первым делом создайте PerformanceObserver:
Флаг buffered: true нужен, чтобы учитывать каждый layout-shift, произошедший до инициализации обсервера. Это особенно полезно для скриптов, библиотек и сторонних систем аналитики, подгружающихся асинхронно.
Каждый коллбек обсервера будет хранить список сдвигов в list.getEntries().
Каждый сдвиг это объект LayoutShift:

Вот его атрибуты:
- duration — всегда 0;
- entryType — всегда layout-shift;
- hadRecentInput — был ли ввод от пользователя в ближайшие 500мс;
- lastInputTime — время последнего ввода;
- name — должно быть layout-shift (в Chrome сейчас это пустая строка “”);
- sources — выборка подробностей о том, что вызвало сдвиг;
- startTime — временная метка сдвига с высокой точностью;
- value — величина сдвига (про величину ниже).
Если вам нужно просто посчитать CLS, вы можете добавить value каждого layout-shift, если его hadRecentInput — false.
Для более детальной информации о сдвигах, добавьте sources.
Если вы хотите просматривать веб страницы и в реальном времени наблюдать изменение CLS, попробуйте этот простой скрипт для Tampermonkey и расширение для Chome — Web Vitals.
Для лабораторных измерений можно использовать:
- Chrome Developer Tools (и расширение для браузера Lighthouse/CLI)
- PageSpeed Insights WebPagetest.org
- layoutstability.rocks
- Web Vitals Chrome Extention
- Calibre
В Chrome Developer Tools у вас есть доступ к аудиту производительности Lighthouse. Перейдите на вкладку Lighthouse и запустите Perfomance Audit:

Кроме CLS верхнего уровня, вы можете просмотреть составляющие его сдвиги:

Здесь видно баг — смещения в IFRAME, которые не влияют на общий балл CLS, но отображаются в списке
Если вы нажмете на кнопку View Original Trace в разделе Аудит, откроется вкладка Perfomance. На вкладке Perfomance теперь есть новый столбец Experience, в котором на временной шкале отображаются отдельные смещения разметки и данные о них.

Помимо трассировки вы можете обнаруживать сдвиги во время просмотра сайта с помощью визуальных индикаторов. Для этого нажмите Rendering в меню More Tools. Затем включите Layout Shift Regions. Теперь во время просмотра страницы сдвиги разметки будут отмечаться голубой подсветкой.
Другие метрики сайтов
Кроме основных метрик, которые Google считает критическими, существуют и дополнительные. Например, метрики: Time to First Byte (TTFB) и First Contentful Paint (FCP) — являются жизненно важными аспектами процесса загрузки и полезны при диагностике проблем с LCP (медленное время отклика сервера или ресурсы блокирующие отрисовку страницы).
Также, такие метрики сайта как: Total Blocking Time (TBT) и Time to Interactive (TTI), измеряются лабораторными методами и помогают обнаружить потенциальные проблемы с интерактивностью страницы.