-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
91 lines (69 loc) · 1.88 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
var debug = require('debug')('load-script-once');
var find = require('find');
var load = require('load-script');
var nextTick = require('next-tick');
var memoize = require('memoize-async');
var url = require('url');
/**
* Memoize our load function
*/
load = memoize(load, canonical);
/**
* Module exports
*/
module.exports = function (options, callback) {
callback = callback || function () {};
var src = typeof options === 'string'
? options
: chooseUrl(options);
if (!src) throw new Error('Could not parse the options!');
debug('loading: %s', src);
var scripts = document.getElementsByTagName('script');
var canonicalized = canonical(src);
var exists = find(scripts, function (script) {
return canonical(script.src) === canonicalized;
});
if (exists) {
debug('exists: %s', src);
return nextTick(callback);
}
load(src, callback);
};
/**
* Return a 'canonical' version of the url (no querystring or hash).
*
* @param {String} href
* @return {String} canonical
*/
function canonical (href) {
var parsed = url.parse(href);
var canonical = '';
if (parsed.protocol) canonical += parsed.protocol;
canonical += '//';
if (parsed.hostname) canonical += parsed.hostname;
if (parsed.pathname) canonical += parsed.pathname;
return canonical;
}
/**
* Chooses a url from the options passed in
*
* @param {Object} options
* @field {String} src src to load from
* @field {String} http http src to load
* @field {String} https https src to load
*/
function chooseUrl (options) {
var protocol = document.location.protocol;
var https = protocol === 'https:' ||
protocol === 'chrome-extension:';
var protocolSrc = https
? options.https
: options.http;
var src = options.src || protocolSrc;
if (src && src.indexOf('//') === 0) {
return https
? 'https:' + src
: 'http:' + src;
}
return src;
}