JS async does not work | LCP issue because of background image, which is set with JS

Viewed 55

I am trying to optimze my website with help of lighthouse.

Lighthouse shows me a bad score for LCP (3-6~ sec). The culprit is a background image, which I load with JS. I already tried to optimize the code and this is how it looks atm.:

window.onload = function() {
    var mobile_content = document.getElementById('content_mob');
    if (mobile_content.offsetParent !== null) {
        // webp or not
        var bgSource = "https://example.cloudfront.net/example/example-img.webp";
        if (document.querySelector('html').classList.contains('no-webp') == true) {
            bgSource = "https://example.cloudfront.net/example/example-img.jpg";
        }
        // Set BG image
        var bg_content = document.querySelector('#content_mob .content_top .bg_img_c');
        bg_content.style.background = "linear-gradient(0deg,#000 0,rgba(0,0,0,.7) 35%,rgba(0,0,0,.4) 50%,rgba(0,0,0,0) 100%),url(" + bgSource + ") no-repeat";
        bg_content.style.backgroundSize = "cover";
        bg_content.style.backgroundPosition = "center";
        bg_content.classList.add("fade-in");
    }
}

In theory async loading this part of the JS should solve the issue, so I moved this code into a seperate JS file, but it does not solve it.

<script src="bg_loading.js" async></script>

I am 100% certain that this is the issue, because if I remove this code, then I am in the greens for LCP (0.7~ sec)

0 Answers
Related