Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Large CSS background-image blocks Javascript while loading

From everything I've been able to find a large CSS background-image shouldn't block javascript from executing. Unfortunately, on both Firefox and Chrome this does seem to be the case.

If I do a hard refresh on Chrome I can see the background slowly load (on a slow connection) and then once it's finished my JavaScript executes, displaying the rest of the page's content.

I'm using jQuery's $(document).ready and Facebook's window.fbAsyncInit methods to run the JavaScript when the DOM and Facebook SDK are ready.

I'm not sure if it's relevant but the background is set in CSS with:

body {
    background: black url(...) no-repeat top center fixed;
    -webkit-background-size: cover;
    background-size: cover;
    background-position: 50% 50%;
}

I am already using CSS Media Queries to load smaller images for smaller screen resolutions and making the background images smaller won't fix the problem; it would just hide the symptoms.

What else should I do to ensure that the background image doesn't block JavaScript execution?

My thought would be to load a dummy background image and then have JavaScript append another stylesheet with the real background images (and media queries for smaller screens) but this seems hacky.

like image 905
Brad Dwyer Avatar asked Mar 10 '13 20:03

Brad Dwyer


1 Answers

Loading a background image doesn't keep Javascript from running. The reason is most likely that loading the image keeps the script from being loaded in the first place.

Browsers have a limitation to the number of requests they run simultaneously against each domain, and similarly web servers have a limitation on the number of requests that it handles simultaneously from the same user. Sometimes the limit is as low as one or two simultaneous downloads.

If you want the script to load before the image, use script so set the background image in the CSS. That way you know that the script has loaded before the image starts loading:

$(document.body).css('background-image', 'url(...)');
like image 171
Guffa Avatar answered Sep 24 '22 22:09

Guffa