Element hide and show causing the Largest Contentful Paint 8000ms

68 views Asked by At

I would like to initially hide an image and then display it only on the first page load, as determined by checking a cookie. However, this approach could lead to issues with the Largest Contentful Paint metric. Do you have any suggestions on how to avoid this problem?

Below is the problematic code:

document.addEventListener('DOMContentLoaded', function () {
  if (!document.cookie.split(';').some((item) => item.trim().startsWith('userEntered='))) {
    document.getElementById('c_img').style.display = 'block';
  }
});
<div id="content" style="height: 100vh;">
  <img id="c_img" src='button.png' style="height: 70px; width:70px; display: none" />
</div>

Showing the image by default and then hiding it if a 'userEntered' cookie is present avoids LCP issues. However, this approach results in the image briefly appearing and then disappearing. Example:

document.addEventListener('DOMContentLoaded', function () {
  if (document.cookie.split(';').some((item) => item.trim().startsWith('userEntered='))) {
    document.getElementById('c_img').style.display = 'none';
  }
});
<div id="content" style="height: 100vh;">
  <img id="c_img" src='button.png' style="height: 70px; width:70px;/>
</div>
1

There are 1 answers

0
Barry Pollard On

Agree with Rick that doing this server side is the best way.

If you must do this client-side, then minimising the time is you best option.

You are running your JS on 'DOMContentLoaded' but if you executed this just afterwards (when you know it's in the DOM), then it would show far quicker and so impact LCP far less:

<div id="content" style="height: 100vh;">
  <img id="c_img" src='button.png' style="height: 70px; width:70px; display: none" />
</div>
<script>
  if (!document.cookie.split(';').some((item) => item.trim().startsWith('userEntered='))) {
    document.getElementById('c_img').style.display = 'block';
  }
</script>

Note there would still be a delay as compiling executing the JS, and reading cookies, does take a small amount of time, but this is the minimum you can do.

Also the image will be downloaded either way (meaning it's wasted if not shown) but that is what you want to reduce LCP impact. And you could add fetchpriority=high to it to get that image loading even quicker.