-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
70 lines (57 loc) · 1.91 KB
/
index.js
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
'use strict';
/*
* Module dependencies.
*/
var onload = require('script-onload');
var tick = require('next-tick');
var type = require('component-type');
/**
* Loads a script asynchronously.
*
* @param {Object} options
* @param {Function} cb
*/
function loadScript(options, cb) {
if (!options) {
throw new Error('Can\'t load nothing...');
}
// Allow for the simplest case, just passing a `src` string.
if (type(options) === 'string') {
options = { src : options };
}
var https = document.location.protocol === 'https:' || document.location.protocol === 'chrome-extension:';
// If you use protocol relative URLs, third-party scripts like Google
// Analytics break when testing with `file:` so this fixes that.
if (options.src && options.src.indexOf('//') === 0) {
options.src = (https ? 'https:' : 'http:') + options.src;
}
// Allow them to pass in different URLs depending on the protocol.
if (https && options.https) {
options.src = options.https;
} else if (!https && options.http) {
options.src = options.http;
}
// Make the `<script>` element and insert it before the first script on the
// page, which is guaranteed to exist since this Javascript is running.
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = options.src;
// If we have a cb, attach event handlers. Does not work on < IE9 because
// older browser versions don't register element.onerror
if (type(cb) === 'function') {
onload(script, cb);
}
tick(function() {
// Append after event listeners are attached for IE.
var firstScript = document.getElementsByTagName('script')[0];
firstScript.parentNode.insertBefore(script, firstScript);
});
// Return the script element in case they want to do anything special, like
// give it an ID or attributes.
return script;
}
/*
* Exports.
*/
module.exports = loadScript;