Home / AJAX

HOW TO Detect DOM Ready

RSS
Modified on 2009/12/04 17:18 by Stephen Walther Categorized as Uncategorized
As a page loads the browser creates an in-memory representation of all the elements defined in the page and places them into the Document Object Model (DOM). Objects dynamically created by scripts are also added to the DOM. The ASP.NET Ajax Library provides several different ways to detect when the DOM Ready event is fired. First, a call to Sys.onReady can be added into the page. When all scripts requested by the page have been loaded and the the DOM is ready to be accessed Sys.onReady will be called automatically:
<script type="text/javascript">

Sys.require([Sys.components.dataView, Sys.scripts.jQuery]);

Sys.onReady(function() { //DOM is ready to access and use });

</script>


Second, a function named pageLoad can be added into the page. This function was available in earlier versions of the ASP.NET Ajax Library.
<script type="text/javascript">

Sys.require([Sys.components.dataView, Sys.scripts.jQuery]);

function pageLoad() { //DOM is ready to access and use }

</script>


Finally, the Script Loader can be used to detect when the DOM Ready event fires. When using Sys.require to load scripts and components in a page this option provides a convenient way to detect the DOM Ready event and is the recommended approach when using the Script Loader. Sys.require defines three different parameters including an array of the scripts and components to load, the function to call when the DOM Ready event fires, and a user context object that can be used to pass state information. By using the Script Loader's second parameter the DOM ready event can be handled without using a separate Sys.onReady call. An example of using the second parameter is shown next:
<script type="text/javascript">

Sys.require([Sys.components.dataView, Sys.scripts.jQuery], domReady);

function domReady() { //DOM is ready to access and use }

</script>


The previous code can be simplified by passing an inline function to Sys.require's second parameter:
<script type="text/javascript">

Sys.require([Sys.components.dataView, Sys.scripts.jQuery], function() { //DOM is ready });

</script>


Once jQuery and the DataView component's supporting scripts are loaded the inline function will automaticaly be invoked.