4

In my understanding when using defer in a script tag which is placed right below a stylesheet, the browser waits for the stylesheet to load (CSSOM) before executing the script and firing DOMContentLoaded. (More about that)

This works in Firefox but not in Chrome, so I made a test case where a huge css file is loaded right before a script tag which is deferred.

The HTML File with the stylesheet and the deferred script.

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="main.css">
    <script src="main.js" defer></script>
</head>
<body>
    <div class="result">Loading...</div>
</body>
</html>

The CSS file contains bootstrap and also a test-class which sets a font-family.

/* ...bootstrap v4 css... */
.test {
    font-family: 'It works!';
}

The JS File contains jQuery and a simple test script.

// ...jQuery....
$(function () {
    $('<meta class="test">').appendTo(document.head);
    var extractedStyles = $('.test').css('font-family');
    $('.result').text(extractedStyles);
});

In Firefox the CSS could be parsed on execution time and I see "It works!" > see Firefox

In Chrome the CSS could not be parsed on execution time and I see "Times New Roman" > see Chrome

If you check the developer tools, DOMContentLoaded has been fired differently in Chrome and Firefox. Firefox fires it right at the end of load of the CSS file (which is why the testcase works) but Chrome doesn't wait for the CSS file to load.

Firefox developer tools

Chrome developer tools

Why is this the case and can anyone explain me how to get around this issue?

EDIT: Chromium confirmed that this behaviour is a bug, see https://bugs.chromium.org/p/chromium/issues/detail?id=792420

0 Answers0