forked from segmentio/load-iframe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
60 lines (49 loc) · 1.97 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
/**
* Module dependencies.
*/
var is = require('is');
var onload = require('script-onload');
var tick = require('next-tick');
/**
* Expose `loadScript`.
*
* @param {Object} options
* @param {Function} fn
* @api public
*/
module.exports = function loadIframe(options, fn){
if (!options) throw new Error('Cant load nothing...');
// Allow for the simplest case, just passing a `src` string.
if (is.string(options)) 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:' + options.src : '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 `<iframe>` element and insert it before the first iframe on the
// page, which is guaranteed to exist since this Javaiframe is running.
var iframe = document.createElement('iframe');
iframe.src = options.src;
iframe.width = options.width || 1;
iframe.height = options.height || 1;
iframe.style.display = 'none';
// If we have a fn, attach event handlers, even in IE. Based off of
// the Third-Party Javascript script loading example:
// https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html
if (is.fn(fn)) {
onload(iframe, fn);
}
tick(function(){
// Append after event listeners are attached for IE.
var firstScript = document.getElementsByTagName('script')[0];
firstScript.parentNode.insertBefore(iframe, firstScript);
});
// Return the iframe element in case they want to do anything special, like
// give it an ID or attributes.
return iframe;
};