Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>$(document).ready()</code> simply ensures that all DOM elements are loaded before your javascript is loaded. </p> <p><strong>When it doesn't matter</strong></p> <p>Without waiting for this event to fire, you may end up manipulating DOM elements or styles that are yet to exist on the page. the DOM ready event also allows you more flexibility to run scripts on different parts of the page. For example:</p> <pre><code>&lt;div id="map"&gt;&lt;/div&gt; &lt;script type="text/javascript"&gt;document.getElementById('map').style.opacity = 0;&lt;/script&gt; </code></pre> <p>will run because the map div has been loaded before the script runs. In fact, you can get some <a href="http://developer.yahoo.com/performance/rules.html" rel="noreferrer">pretty good performance improvements</a> by placing your scripts at the bottom of the page.</p> <p><strong>When it does matter</strong></p> <p>However, if you are loading your scripts in the <code>&lt;head&gt;</code> element, most of your DOM has not loaded. This example will not work:</p> <pre><code>&lt;script type="text/javascript"&gt;document.getElementById('map').style.opacity = 0;&lt;/script&gt; &lt;div id="map"&gt;&lt;/div&gt; </code></pre> <p>will not, since the map div has not been loaded. </p> <p><strong>A safe solution</strong></p> <p>You can avoid this by simply wait until the entire DOM has loaded:</p> <pre><code>&lt;script type="text/javascript"&gt;$(document).ready(function () { document.getElementById('map').style.opacity = 0; }); &lt;/script&gt; &lt;div id="map"&gt;&lt;/div&gt; </code></pre> <p>There are plenty of <a href="http://www.learningjquery.com/2006/09/introducing-document-ready" rel="noreferrer">articles</a> that explain this, as well as the <a href="http://api.jquery.com/ready/" rel="noreferrer">jQuery documentation</a> itself.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload