├── .eslintrc.js ├── .gitignore ├── .npmignore ├── .pakit.json ├── .travis.yml ├── LICENSE ├── README.md ├── package-lock.json ├── package.json └── src └── load-js.js /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | "parserOptions": { 3 | "sourceType": "module" 4 | }, 5 | "env": { 6 | "browser": true, 7 | "commonjs": true 8 | }, 9 | "rules": { 10 | "curly": 2, 11 | "no-console": 0, 12 | "no-debugger": 2, 13 | "no-alert": 2, 14 | "no-use-before-define": 0, 15 | "no-underscore-dangle": 0, 16 | "no-multi-spaces": 0, 17 | "no-unused-vars": 1, 18 | "semi": 0, 19 | "global-strict": 0, 20 | "wrap-iife": [2, "inside"], 21 | "quotes": [1, "double"], 22 | "key-spacing": 0, 23 | "no-trailing-spaces": 0, 24 | "eol-last": 2 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 18 | .grunt 19 | 20 | # node-waf configuration 21 | .lock-wscript 22 | 23 | # Compiled binary addons (http://nodejs.org/api/addons.html) 24 | build/Release 25 | 26 | # Dependency directory 27 | node_modules 28 | 29 | # Optional npm cache directory 30 | .npm 31 | 32 | # Optional REPL history 33 | .node_repl_history 34 | index.js.map 35 | index.js 36 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .travis.yml 2 | -------------------------------------------------------------------------------- /.pakit.json: -------------------------------------------------------------------------------- 1 | { 2 | "umd": "loadJS", 3 | "builtins": false 4 | } 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "4" 4 | 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Miguel Castillo 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # load-js 2 | 3 | [![Greenkeeper badge](https://badges.greenkeeper.io/MiguelCastillo/load-js.svg)](https://greenkeeper.io/) 4 | 5 | Promise based script loader for the browser using script tags. 6 | 7 | This is a UMD module, so feel free to include it in your nodejs bundling pipeline or directly in the browser via script tags. 8 | 9 | > Promise implementation needs to be polyfilled if environment does not already provide it. 10 | 11 | # usage 12 | 13 | ## install 14 | 15 | ``` 16 | $ npm install load-js 17 | ``` 18 | 19 | ## api 20 | 21 | loadJS is a method that loads scripts concurrently using script tags. loadJS takes in a single or an array of items where the items can be just a url string, or a config object with options for configuring: 22 | 23 | - `type`: defaults to `text/javascript`. 24 | - `async`: defaults to `false`. 25 | - `charset`: defaults to `utf-8`. 26 | - `id`: no default value. 27 | - `url`: Location of the script to load. Required if no `text` is provided. 28 | - `text`: Script text to execute. Required if no `url` is provided. 29 | - `cache`: flag to determine if item with ID or URL is to be cached. defaults to `true`. 30 | - `allowExternal`: flag to handle situations when the DOM already has a script element with the same ID or URL as what loadJS is being told to load. By default, loadJS will use script elements that already exist in the DOM. To turn off this behavior, set `allowExternal` to false. 31 | - `debug`: flag to show debug message. defaults to `false`. 32 | 33 | Some of these options are described in detail [here](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script). 34 | 35 | > text and url are mutually exclusive and you must specify one. If you call loadJS with a string as a parameter that string will be treated as a url. If you specify both, then url will be used. 36 | 37 | The `async` flag will enable the browsers ability load and execute scripts as soon as possible. This means that scripts are likely going to excute out of order. Because of the nondeterministic script execution nature of `async`, it is defaulted to false. 38 | 39 | The elaborate more on the `allowExternal` flag. As explained in the options, this flag is particularly useful for handling situations when the DOM already has script elements with the same ID or URL as what loadJS is supposed to load. For example, if a script element with a URL `https://awesome.cdn/react.js` already exists in the DOM, and for some reason you ask loadJS to load that same URL, loadJS by default will return what already exists in the DOM instead of loading a new script. In order for loadJS to ignore what's already in the DOM and load its own script you need to set `allowExternal` to false. 40 | 41 | ## examples 42 | 43 | Let's just give a simple example where `load-js` is loaded via a script tag in you HTML 44 | 45 | ``` html 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 61 | 62 | 63 | 64 | 65 | 66 | ``` 67 | 68 | Another example configuring the script execution to be asynchonous 69 | 70 | ``` javascript 71 | loadJS([{ 72 | async: true, 73 | url: "https://code.jquery.com/jquery-2.2.1.js" 74 | }, { 75 | async: true, 76 | url: "https://unpkg.com/react@15.3.1/dist/react.min.js" 77 | }]) 78 | .then(() => { 79 | console.log("all done!"); 80 | }); 81 | ``` 82 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "load-js", 3 | "version": "3.1.1", 4 | "description": "Promise based script loader for the browser using script tags", 5 | "main": "index.js", 6 | "scripts": { 7 | "prepublish": "pakit src/load-js.js --out index.js", 8 | "build": "pakit src/load-js.js --out index.js" 9 | }, 10 | "repository": { 11 | "type": "git", 12 | "url": "https://github.com/MiguelCastillo/load-js.git" 13 | }, 14 | "author": "Miguel Castillo ", 15 | "license": "MIT", 16 | "bugs": { 17 | "url": "https://github.com/MiguelCastillo/load-js/issues" 18 | }, 19 | "homepage": "https://github.com/MiguelCastillo/load-js", 20 | "devDependencies": { 21 | "pakit": "^1.0.2" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/load-js.js: -------------------------------------------------------------------------------- 1 | function createLoadJS() { 2 | var cache = {}; 3 | var head = document.getElementsByTagName("head")[0] || document.documentElement; 4 | 5 | function exec(options) { 6 | if (typeof options === "string") { 7 | options = { 8 | url: options, 9 | debug: false 10 | }; 11 | } 12 | 13 | var cacheId = options.id || options.url; 14 | var cacheEntry = cache[cacheId]; 15 | 16 | if (cacheEntry) { 17 | if (!!options.debug) { 18 | console.log("load-js: cache hit", cacheId); 19 | } 20 | return cacheEntry; 21 | } 22 | else if (options.allowExternal !== false) { 23 | var el = getScriptById(options.id) || getScriptByUrl(options.url); 24 | 25 | if (el) { 26 | var promise = Promise.resolve(el); 27 | 28 | if (cacheId) { 29 | cache[cacheId] = promise; 30 | } 31 | 32 | return promise; 33 | } 34 | } 35 | 36 | if (!options.url && !options.text) { 37 | throw new Error("load-js: must provide a url or text to load"); 38 | } 39 | 40 | var pending = (options.url ? loadScript : runScript)(head, createScript(options)); 41 | 42 | if (cacheId && options.cache !== false) { 43 | cache[cacheId] = pending; 44 | } 45 | 46 | return pending; 47 | } 48 | 49 | function runScript(head, script) { 50 | head.appendChild(script); 51 | return Promise.resolve(script); 52 | } 53 | 54 | function loadScript(head, script) { 55 | return new Promise(function(resolve, reject) { 56 | // Handle Script loading 57 | var done = false; 58 | 59 | // Attach handlers for all browsers. 60 | // 61 | // References: 62 | // http://stackoverflow.com/questions/4845762/onload-handler-for-script-tag-in-internet-explorer 63 | // http://stevesouders.com/efws/script-onload.php 64 | // https://www.html5rocks.com/en/tutorials/speed/script-loading/ 65 | // 66 | script.onload = script.onreadystatechange = function() { 67 | if (!done && (!script.readyState || script.readyState === "loaded" || script.readyState === "complete")) { 68 | done = true; 69 | 70 | // Handle memory leak in IE 71 | script.onload = script.onreadystatechange = null; 72 | resolve(script); 73 | } 74 | }; 75 | 76 | script.onerror = reject; 77 | 78 | head.appendChild(script); 79 | }); 80 | } 81 | 82 | function createScript(options) { 83 | var script = document.createElement("script"); 84 | script.charset = options.charset || "utf-8"; 85 | script.type = options.type || "text/javascript"; 86 | script.async = !!options.async; 87 | script.id = options.id || options.url; 88 | script.loadJS = "watermark"; 89 | 90 | if (options.url) { 91 | script.src = options.url; 92 | } 93 | 94 | if (options.text) { 95 | script.text = options.text; 96 | } 97 | 98 | return script; 99 | } 100 | 101 | function getScriptById(id) { 102 | var script = id && document.getElementById(id); 103 | 104 | if (script && script.loadJS !== "watermark") { 105 | console.warn("load-js: duplicate script with id:", id); 106 | return script; 107 | } 108 | } 109 | 110 | function getScriptByUrl(url) { 111 | var script = url && document.querySelector("script[src='" + url + "']"); 112 | 113 | if (script && script.loadJS !== "watermark") { 114 | console.warn("load-js: duplicate script with url:", url); 115 | return script; 116 | } 117 | } 118 | 119 | return function load(items) { 120 | return items instanceof Array ? 121 | Promise.all(items.map(exec)) : 122 | exec(items); 123 | } 124 | } 125 | 126 | module.exports = createLoadJS(); 127 | module.exports.create = createLoadJS; 128 | --------------------------------------------------------------------------------