initial commit
[m6w6/m6w6.github.io] / _posts / 2011-03-18-javascript-delaying.md
1 ---
2 title: Javascript delaying
3 author: m6w6
4 tags:
5 - WEB
6 ---
7
8 In need of executing Javascript after the page has loaded, or something else
9 has been initialized I came up with a simple but useful tiny "Delayer":
10
11 ```js
12 /**
13 * @param handler a callback accepting Delayer.dispatch as argument
14 */
15 function Delayer(handler) {
16 var self = this;
17
18 this.dispatch = function() {
19 for (var i = 0; i < self.length; ++i) {
20 console.log("running delayed init "+i+": "+self[i]);
21 self[i]();
22 }
23 };
24
25 if (typeof handler == "function" || handler instanceof Function) {
26 handler(this.dispatch);
27 }
28 }
29
30 Delayer.prototype = Array.prototype;
31 ```
32
33 It can be initialized the following way:
34 ```js
35 /* e.g. with jQuery */
36 window.delayedInits = new Delayer($(document).ready);
37 /* e.g. with Facebook */
38 window.fbDelayedInits = new Delayer(function(dp){window.fbAsyncInit = dp;});
39 ```
40
41 Then you push your work the usual way:
42 ```js
43 delayedInits.push(function() {alert("Hello, delayed!");});
44 ```