I am developing a static website. I am appending CSS style-sheet to document head using JavaScript. After CSS loads I do some calculations based on position and dimensions of elements. So it is mandatory for CSS to load first and then calculate.
But the problem is that Chrome browser waits for script to execute and while it appends stylesheet to head but doesn't actually download it, and hence document.stylesheets
does not update!
This problem is only with chrome. Firefox downloads it instantly as expected!
I have created a sample code to easily demonstrate the problem
<!DOCTYPE html>
<head></head>
<body>
<p id='status'></p>
<button onclick="updateStatus()">updateStatus</button>
<script>
const link = document.createElement('link')
link.rel = 'stylesheet'
link.href = './style.css'
document.head.appendChild(link)
updateStatus()
function updateStatus() {
document.getElementById('status').innerHTML = document.styleSheets.length;
}
</script>
</body>
</html>
Try opening this question in chrome and Firefox. If you run snippet in Chrome it will increment by one, means the CSS is loaded later. On the other hand, Firefox value does not change means it has loaded CSS first.
How can I force chrome or any other browser to load CSS first and then continue JavaScript execution?
I have tried attaching onload
event (also suggested here) to stylesheet and it works, but my code is large and multipurpose. I can't split it into pre-CSS and post-CSS parts!