Consider this scenario: you have a webpage with a common structure in the <head>
:
<link rel="stylesheet" href="styles.css"> // large CSS bundle
<script defer src="main.js"></script> // small JS bundle with defer attribute
There is also a
<span id="element"></span>
on the page.
The CSS bundle includes #element { display: none; }
.
The JS bundle contains (using jquery):
$(document).ready(() => {
console.log($('#element').css('display'));
});
However, the outcome can vary. Sometimes the JS executes before the CSS, resulting in 'inline'. Other times, it executes after the CSS, yielding 'none' as desired.
To ensure that my JS bundle is non-blocking, I use the deferred attribute. Placing the JS bundle at the end of the page is not an option due to using turbolinks, which restricts this practice (source).
Using window:load
isn't ideal either, as it fires once all resources are downloaded, including images.
I aim for a solution where the JS is non-blocking and executes after the CSS for consistent and predictable results. Is there a way to achieve this?