EN
JavaScript - on style load event
0
points
In this article, we would like to show you how to handle style load event using JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
<style>
/* web page styles here */
</style>
<script>
var style = document.querySelector('style');
style.onload = function load() {
console.log('The style has been loaded successfully.');
}
</script>
or:
// ONLINE-RUNNER:browser;
<style>
/* web page styles here */
</style>
<script>
var style = document.querySelector('style');
style.addEventListener('load', (event) => {
console.log('The style has been loaded successfully.');
});
</script>
Practical examples
Example 1
In this example, we add a function to the window.onload property, which will be executed on successful script loading.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
/* web page styles here */
</style>
<script>
var style = document.querySelector('style');
style.onload = function load() {
console.log('The style has been loaded successfully.');
}
</script>
</head>
<body> Web page body... </body>
</html>
Example 2
In this example, we add an event listener to the window object, which executes a function on a script load event.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
/* web page styles here */
</style>
<script>
var style = document.querySelector('style');
style.addEventListener('load', (event) => {
console.log('The style has been loaded successfully.');
});
</script>
</head>
<body> Web page body... </body>
</html>