Subversion Repositories eFlore/Applications.moissonnage

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
6 delphine 1
L.DeferredLayer = L.LayerGroup.extend({
2
	options: {
3
		js: [],
4
		init: null
5
	},
6
 
7
	_script_cache: {},
8
 
9
	initialize: function(options) {
10
		L.Util.setOptions(this, options);
11
		L.LayerGroup.prototype.initialize.apply(this);
12
		this._loaded = false;
13
	},
14
 
15
	onAdd: function(map) {
16
		L.LayerGroup.prototype.onAdd.apply(this, [map]);
17
		if (this._loaded) return;
18
		//console.info("Script cache", this._script_cache);
19
		var loaded = function() {
20
			//console.info("Loaded", this, this.options);
21
			this._loaded = true;
22
			var l = this.options.init();
23
			if (l)
24
				this.addLayer(l);
25
		}
26
		this._loadScripts(this.options.js.reverse(), L.Util.bind(loaded, this));
27
	},
28
 
29
	_loadScripts: function(scripts, cb, args) {
30
		if (!scripts || scripts.length == 0)
31
			return cb(args);
32
		var _this = this, s = scripts.pop(), c;
33
		c = this._script_cache[s];
34
		if (c === undefined) {
35
			c = {url: s, wait: []};
36
			//console.info("Load ", s);
37
			var script = document.createElement('script');
38
			script.src = s;
39
			script.type = 'text/javascript';
40
			script.onload = function () {
41
				//console.info("Element(cb)", c.e.readyState);
42
				c.e.readyState = "completed";
43
				var i = 0;
44
				for (i = 0; i < c.wait.length; i++)
45
					c.wait[i]();
46
			}
47
			c.e = script;
48
			document.getElementsByTagName('head')[0].appendChild(script);
49
		}
50
		function _cb() { _this._loadScripts(scripts, cb, args); }
51
		c.wait.push(_cb);
52
		//console.info("Element", c.e.readyState);
53
		if (c.e.readyState == "completed")
54
			_cb();
55
		this._script_cache[s] = c;
56
	}
57
});