Document Ready

Know when the document or various files have finished loading

The best way to not block rendering of a page is to not put JS all over the page. The best practice is to put all your CSS in the <head> and all your JS right before the </body>

Unfortunately this is not always possible, since often various elements depend on certain JS before getting to the </body>. To work around this we can push functions downwards to be able to execute them later when all the JS has finished loading.

{% highlight html %} {% endhighlight %}

Even when not depending on something like jQuery, if we should have inline scripts, it is always faster and safer to push the execution of those scripts to the bottom.

{% highlight html %} {% endhighlight %}

head.ready() takes the following arguments

{% highlight js %} // Attention: subtility here head.ready(function() { // push a function to the end of the page for later execution // runs once all files have finished loading // WARNING: if no files are cued for loading this will NOT trigger ! }); head.ready(document, function() { // push a function to the end of the page for later execution // runs as soon as the document is ready }); head.ready("file1.js", function() { // execute this function, only when file1.js has finished loading // used in conjunction with head.load("file1.js"); }); head.ready(["file1.js", "file2.js"], function() { // execute this function, only when file1.js AND file2.js has finished loading // used in conjunction with head.load("file1.js", "file2.js"); }); head.ready("label1", function() { // execute this function, only when label1 has finished loading // used in conjunction with head.load({ label1: "file1.js" }); }); head.ready(["label1", "label2"], function() { // execute this function, only when label1 AND label2 has finished loading // used in conjunction with head.load([{ label1: "file1.js" }, { label2: "file2.js" }]); }); {% endhighlight %}

Show Comments