Skip to content

Commit 3377472

Browse files
Callback is now (error, event) and it listens to the error event on the script tag.
1 parent 402fda5 commit 3377472

File tree

3 files changed

+22
-6
lines changed

3 files changed

+22
-6
lines changed

index.js

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,17 @@ module.exports = function loadScript (options, callback) {
3535
// https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html
3636
if (callback && type(callback) === 'function') {
3737
if (script.addEventListener) {
38-
script.addEventListener('load', callback, false);
38+
script.addEventListener('load', function (event) {
39+
callback(null, event);
40+
}, false);
41+
script.addEventListener('error', function (event) {
42+
callback(new Error('Failed to load the script.'), event);
43+
}, false);
3944
} else if (script.attachEvent) {
40-
script.attachEvent('onreadystatechange', function () {
41-
if (/complete|loaded/.test(script.readyState)) callback();
45+
script.attachEvent('onreadystatechange', function (event) {
46+
if (/complete|loaded/.test(script.readyState)) {
47+
callback(null, event);
48+
}
4249
});
4350
}
4451
}

test/index.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
<div id="mocha"></div>
77
<script src="mocha.js"></script>
88
<script>mocha.setup({
9+
timeout : 10000,
910
ui : 'qunit',
1011
ignoreLeaks : true
1112
})</script>

test/tests.js

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
suite('load-script');
88

99
test('can load by src string with callback', function (done) {
10-
load('//cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.1/angular.min.js', function () {
10+
load('//cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.1/angular.min.js', function (error, event) {
11+
assert(!error);
1112
done();
1213
});
1314
});
@@ -17,17 +18,24 @@
1718
assert(type(script) === 'element');
1819
});
1920

20-
2121
test('can load protocol-specific src', function (done) {
2222
var http = 'http://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js';
2323
var https = 'https://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js';
2424
var script = load({
2525
http : http,
2626
https : https
27-
}, function () {
27+
}, function (error, event) {
28+
assert(!error);
2829
done();
2930
});
3031
assert(script.src === http);
3132
});
3233

34+
test('callback passes an error when the script fails to load', function (done) {
35+
load('//cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.1/nonexistent.min.js', function (error, event) {
36+
assert(error);
37+
done();
38+
});
39+
});
40+
3341
}());

0 commit comments

Comments
 (0)