In this way you will form some sort of chainable javascript library loading, which will guarantee you that every file will be loaded only then when it has its dependencies loaded.
This object is useful when you want to load external javascript files only when last one was loaded.
In this way you will form some sort of chainable javascript library loading, which will guarantee you that every file will be loaded only then when it has its dependencies loaded.
Usage
This example shows how to load jQuery library and only when its fully loaded then load jQuery UI library, and only then your scripts – “your-script.js”.
Source of the library
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
/**
*
* Chainable external javascript file loading
* http://www.webtoolkit.info/
*
**/
scriptLoader.load([
'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js',
'http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js'
'/your_script.js'
]);
var scriptLoader = {
_loadScript: function (url, callback) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
if (callback) {
script.onreadystatechange = function () {
if (this.readyState == 'loaded') callback();
}
script.onload = callback;
}
head.appendChild(script);
},
load: function (items, iteration) {
if (!iteration) iteration = 0;
if (items[iteration]) {
scriptLoader._loadScript(
items[iteration],
function () {
scriptLoader.load(items, iteration+1);
}
)
}
}
}
|