Javascript DOMContentLoaded listener example

DOMContentLoaded event is fired when document DOM is ready and before images, etc. are loaded. It is similar to jQuery $(document).ready(). Here is code snippet for using it in vanilla Javascript.

<div id="log">
</div>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", listener1);
document.addEventListener("DOMContentLoaded", listener2);
function listener1 () {
  document.querySelector("#log").innerHTML += "in listener1<br/>"; 
}
function listener2 () {
  document.querySelector("#log").innerHTML += "in listener2<br/>"; 
}
</script>
refresh

Note that it works in mode modern browsers including IE9 and above.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments