Consider the following HTML document:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
body {
background: crimson;
}
div {
transition: opacity 5s;
font-size: 4em;
opacity: 0;
}
.loaded div {
opacity: 1;
}
</style>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('body').className += "loaded";
})
</script>
</head>
<body id="body">
<div>
TEST
</div>
</body>
</html>
The div is supposed to have its opacity set to 0 and a 5s transition on opacity.
When the DOM is loaded, the body is given a class that set the div opacity to 1.
I'm expecting the div opacity to transition from 0 to 1 in 5s. But for some reason, it happens immediately.
If I use setTimemout, every works as expected:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
body {
background: crimson;
}
div {
transition: opacity 5s;
font-size: 4em;
opacity: 0;
}
.loaded div {
opacity: 1;
}
</style>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
setTimeout(function() {
document.getElementById('body').className += "loaded";
}, 0);
})
</script>
</head>
<body id="body">
<div>
TEST
</div>
</body>
</html>
Makes me wonder is styles are loaded after DOMContentLoaded event is triggered. Is this a normal behavior or am I doing something wrong here ?