Repository: lukechilds/when-dom-ready Branch: master Commit: 0f19b22cf73c Files: 11 Total size: 10.0 KB Directory structure: gitextract_0zpa3o4g/ ├── .github/ │ └── FUNDING.yml ├── .gitignore ├── .npmignore ├── .travis.yml ├── LICENSE ├── README.md ├── package.json ├── rollup.config.js ├── src/ │ └── index.js └── test/ ├── types.js └── unit.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ github: - 'lukechilds' custom: - 'https://blockstream.info/address/1LukeQU5jwebXbMLDVydeH4vFSobRV9rkj' - 'https://blockstream.info/address/3Luke2qRn5iLj4NiFrvLBu2jaEj7JeMR6w' - 'https://blockstream.info/address/bc1qlukeyq0c69v97uss68fet26kjkcsrymd2kv6d4' - 'https://tippin.me/@lukechilds' ================================================ FILE: .gitignore ================================================ ## Project dist ## Node # Logs logs *.log npm-debug.log* # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage # nyc test coverage .nyc_output # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) .grunt # node-waf configuration .lock-wscript # Compiled binary addons (http://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules jspm_packages # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Optional REPL history .node_repl_history ## OS X *.DS_Store .AppleDouble .LSOverride # Icon must end with two \r Icon # Thumbnails ._* # Files that might appear in the root of a volume .DocumentRevisions-V100 .fseventsd .Spotlight-V100 .TemporaryItems .Trashes .VolumeIcon.icns .com.apple.timemachine.donotpresent # Directories potentially created on remote AFP share .AppleDB .AppleDesktop Network Trash Folder Temporary Items .apdisk ================================================ FILE: .npmignore ================================================ src ================================================ FILE: .travis.yml ================================================ language: node_js node_js: node script: npm run lint && npm test after_success: npm run coverage notifications: email: on_success: never ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2016 Luke Childs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # when-dom-ready > $(document).ready() for the 21st century [![Build Status](https://travis-ci.org/lukechilds/when-dom-ready.svg?branch=master)](https://travis-ci.org/lukechilds/when-dom-ready) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/when-dom-ready/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/when-dom-ready?branch=master) [![npm](https://img.shields.io/npm/v/when-dom-ready.svg)](https://www.npmjs.com/package/when-dom-ready) [![GitHub Donate](https://badgen.net/badge/GitHub/Sponsor/D959A7?icon=github)](https://github.com/sponsors/lukechilds) [![Bitcoin Donate](https://badgen.net/badge/Bitcoin/Donate/F19537?icon=bitcoin)](https://lu.ke/tip/bitcoin) [![Lightning Donate](https://badgen.net/badge/Lightning/Donate/F6BC41?icon=bitcoin-lightning)](https://lu.ke/tip/lightning) Returns a Promise for cleaner usage, provides a Promise chain helper function and can also be used as a pure function. The Promise will resolve instantly if the DOM is already ready. ## Browser Compatibility - IE9+ (requires Promise polyfill) - Edge * - Firefox 29+ - Safari 8+ - Chrome 33+ - Opera 23+ ## Install ```shell npm install --save when-dom-ready ``` or for quick testing: ```html ``` ## Usage ```js import whenDomReady from 'when-dom-ready'; whenDomReady().then(() => console.log('DOM is ready yo!')); ``` You can still use callbacks if you want to: ```js whenDomReady(() => console.log('DOM is ready yo!')); ``` ## Promise chain helper There is also a little helper function, `whenDomReady.resume()`, that pauses the execution of a Promise chain and then resumes it with the last value once the DOM is ready. This allows you to specify complex async control flow in simple readable code: ```js fetch('/my-badass-api.json') .then(getSomeProcessingDoneWhileWaitingForDom) .then(whenDomReady.resume()) .then(injectDataIntoDom); ``` ## Pure usage You can make the function pure by passing in a `document` object. This is really [useful for tests](https://github.com/lukechilds/when-dom-ready/blob/master/test/unit.js) and mocking environments. For example this works in Node.js: ```js const Window = require('window'); const whenDomReady = require('when-dom-ready'); const { document } = new Window(); whenDomReady(document).then(() => console.log('DOM is ready yo!')); ``` Again, you can use the callback version as a pure function too: ```js whenDomReady(() => console.log('DOM is ready yo!'), document); ``` And of course the helper: ```js //... .then(whenDomReady.resume(document)) ``` ## License MIT © Luke Childs ================================================ FILE: package.json ================================================ { "name": "when-dom-ready", "version": "1.2.12", "description": "$(document).ready() for the 21st century", "main": "dist/index.umd.js", "module": "dist/index.es2015.js", "scripts": { "prebuild": "rm -rf dist", "build": "rollup -c", "pretest": "npm run build", "lint": "xo", "test": "nyc ava", "coverage": "nyc report --reporter=text-lcov | coveralls", "prepublish": "npm run build" }, "babel": { "presets": [ [ "es2015", { "modules": false } ] ], "plugins": [ "array-includes" ] }, "xo": { "env": "browser", "extends": "xo-lukechilds" }, "repository": { "type": "git", "url": "git+https://github.com/lukechilds/when-dom-ready.git" }, "keywords": [ "check", "dom", "loaded", "ready", "promise", "async", "asynchronous", "pure" ], "author": "Luke Childs (http://lukechilds.co.uk)", "license": "MIT", "bugs": { "url": "https://github.com/lukechilds/when-dom-ready/issues" }, "homepage": "https://github.com/lukechilds/when-dom-ready", "dependencies": {}, "devDependencies": { "ava": "^0.25.0", "babel-plugin-array-includes": "^2.0.3", "babel-preset-es2015": "^6.24.1", "camelcase": "^4.0.0", "coveralls": "^3.0.0", "eslint-config-xo-lukechilds": "^1.0.0", "nyc": "^11.0.2", "rollup": "^0.52.0", "rollup-plugin-babel": "^2.7.1", "window": "^4.2.1", "xo": "^0.18.2" } } ================================================ FILE: rollup.config.js ================================================ import babel from 'rollup-plugin-babel'; import camelCase from 'camelcase'; const pkg = require('./package.json'); export default { entry: 'src/index.js', plugins: [ babel() ], targets: [ { dest: pkg.main, format: 'umd', moduleName: camelCase(pkg.name), sourceMap: true }, { dest: pkg.module, format: 'es', sourceMap: true } ] }; ================================================ FILE: src/index.js ================================================ /* eslint no-void: "off" */ // Loaded ready states const loadedStates = ['interactive', 'complete']; // Return Promise const whenDomReady = (cb, doc) => new Promise(resolve => { // Allow doc to be passed in as the lone first param if (cb && typeof cb !== 'function') { doc = cb; cb = null; } // Use global document if we don't have one doc = doc || window.document; // Handle DOM load const done = () => resolve(void (cb && setTimeout(cb))); // Resolve now if DOM has already loaded // Otherwise wait for DOMContentLoaded if (loadedStates.includes(doc.readyState)) { done(); } else { doc.addEventListener('DOMContentLoaded', done); } }); // Promise chain helper whenDomReady.resume = doc => val => whenDomReady(doc).then(() => val); export default whenDomReady; ================================================ FILE: test/types.js ================================================ import test from 'ava'; import Window from 'window'; import whenDomReady from '../'; test('whenDomReady is a function', t => { t.is(typeof whenDomReady, 'function'); }); test('whenDomReady returns a Promise', t => { const { document } = new Window(); t.true(whenDomReady(document) instanceof Promise); }); test('whenDomReady.resume is a function', t => { t.is(typeof whenDomReady.resume, 'function'); }); test('whenDomReady.resume returns a function that returns a promise', t => { const { document } = new Window(); const returnValue = whenDomReady.resume(document); t.is(typeof returnValue, 'function'); t.true(returnValue() instanceof Promise); }); test('Promise value always resolves to undefined', async t => { t.plan(2); const { document } = new Window(); const promises = [ whenDomReady(() => 'foo', document).then(val => t.is(val, undefined)), whenDomReady(document).then(val => t.is(val, undefined)) ]; await Promise.all(promises); }); ================================================ FILE: test/unit.js ================================================ import EventEmitter from 'events'; import test from 'ava'; import Window from 'window'; import whenDomReady from '../'; test.cb('callback fires', t => { t.plan(1); const { document } = new Window(); whenDomReady(() => { t.pass(); t.end(); }, document); }); test('Promise resolves', async t => { const { document } = new Window(); t.plan(1); await whenDomReady(document).then(() => t.pass()); }); test('Promise chain helper passes value through', async t => { const { document } = new Window(); t.plan(1); await Promise .resolve('foo') .then(whenDomReady.resume(document)) .then(val => t.is(val, 'foo')); }); test('If document.readyState is already "interactive" run cb', async t => { const document = { readyState: 'interactive' }; t.plan(1); await whenDomReady(document).then(() => t.pass()); }); test('If document.readyState is already "complete" run cb', async t => { const document = { readyState: 'complete' }; t.plan(1); await whenDomReady(document).then(() => t.pass()); }); test('If document.readyState is "loading" run cb on DOMContentLoaded event', async t => { const document = new EventEmitter(); document.addEventListener = document.on; document.readyState = 'loading'; t.plan(1); setTimeout(() => document.emit('DOMContentLoaded'), 500); await whenDomReady(document).then(() => t.pass()); });