UNPKG

@segment/load-script

Version:

Dynamically and asynchronously load a script file.

71 lines (57 loc) 1.96 kB
'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;