├── .eslintrc
├── .gitignore
├── CHANGELOG.md
├── CONTRIBUTING.md
├── IdleQueue.mjs
├── IdleValue.mjs
├── LICENSE
├── README.md
├── defineIdleProperties.mjs
├── defineIdleProperty.mjs
├── docs
├── IdleQueue.md
├── IdleValue.md
├── defineIdleProperties.md
├── defineIdleProperty.md
└── idle-callback-polyfills.md
├── idle-callback-polyfills.mjs
├── lib
├── now.mjs
└── queueMicrotask.mjs
├── package-lock.json
├── package.json
└── test
├── IdleQueue-test.mjs
├── IdleValue-test.mjs
├── defineIdleProperties-test.mjs
├── defineIdleProperty-test.mjs
├── helpers.mjs
├── idle-callback-polyfills-test.mjs
└── index.html
/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | 'root': true,
3 | 'env': {
4 | 'browser': true,
5 | 'es6': true,
6 | 'node': true,
7 | 'mocha': true
8 | },
9 | 'globals': {
10 | 'assert': false,
11 | 'sinon': false,
12 | 'safari': false
13 | },
14 | 'parserOptions': {
15 | 'ecmaVersion': 2018,
16 | 'sourceType': 'module'
17 | },
18 | 'extends': [
19 | 'eslint:recommended',
20 | 'google'
21 | ],
22 | 'rules': {
23 | 'max-len': [2, {
24 | 'code': 80,
25 | 'tabWidth': 2,
26 | 'ignoreUrls': true,
27 | // Ignore `it()` blocks in tests.
28 | 'ignorePattern': 'it\(`'
29 | }]
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | node_modules
3 | npm-debug.log
4 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ### 0.1.1 (2018-10-23)
4 |
5 | - Fix `IdleDealine` typo ([#13](https://github.com/GoogleChromeLabs/idlize/pull/13))
6 |
7 | ### 0.1.0 (2018-09-20)
8 |
9 | - Initial public release
10 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # How to Contribute
2 |
3 | We'd love to accept your patches and contributions to this project. There are
4 | just a few small guidelines you need to follow.
5 |
6 | ## Contributor License Agreement
7 |
8 | Contributions to this project must be accompanied by a Contributor License
9 | Agreement. You (or your employer) retain the copyright to your contribution;
10 | this simply gives us permission to use and redistribute your contributions as
11 | part of the project. Head over to to see
12 | your current agreements on file or to sign a new one.
13 |
14 | You generally only need to submit a CLA once, so if you've already submitted one
15 | (even if it was for a different project), you probably don't need to do it
16 | again.
17 |
18 | ## Code reviews
19 |
20 | All submissions, including submissions by project members, require review. We
21 | use GitHub pull requests for this purpose. Consult
22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
23 | information on using pull requests.
24 |
25 | ## Community Guidelines
26 |
27 | This project follows [Google's Open Source Community
28 | Guidelines](https://opensource.google.com/conduct/).
29 |
--------------------------------------------------------------------------------
/IdleQueue.mjs:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | import {cIC, rIC} from './idle-callback-polyfills.mjs';
18 | import {now} from './lib/now.mjs';
19 | import {queueMicrotask} from './lib/queueMicrotask.mjs';
20 |
21 |
22 | const DEFAULT_MIN_TASK_TIME = 0;
23 |
24 | const isSafari_ = !!(typeof safari === 'object' && safari.pushNotification);
25 |
26 | /**
27 | * A class wraps a queue of requestIdleCallback functions for two reasons:
28 | * 1. So other callers can know whether or not the queue is empty.
29 | * 2. So we can provide some guarantees that the queued functions will
30 | * run in unload-type situations.
31 | */
32 | export class IdleQueue {
33 | /**
34 | * Creates the IdleQueue instance and adds lifecycle event listeners to
35 | * run the queue if the page is hidden (with fallback behavior for Safari).
36 | * @param {{
37 | * ensureTasksRun: boolean,
38 | * defaultMinTaskTime: number,
39 | * }=} param1
40 | */
41 | constructor({
42 | ensureTasksRun = false,
43 | defaultMinTaskTime = DEFAULT_MIN_TASK_TIME,
44 | } = {}) {
45 | this.idleCallbackHandle_ = null;
46 | this.taskQueue_ = [];
47 | this.isProcessing_ = false;
48 | this.state_ = null;
49 | this.defaultMinTaskTime_ = defaultMinTaskTime;
50 | this.ensureTasksRun_ = ensureTasksRun;
51 |
52 | // Bind methods
53 | this.runTasksImmediately = this.runTasksImmediately.bind(this);
54 | this.runTasks_ = this.runTasks_.bind(this);
55 | this.onVisibilityChange_ = this.onVisibilityChange_.bind(this);
56 |
57 | if (this.ensureTasksRun_) {
58 | addEventListener('visibilitychange', this.onVisibilityChange_, true);
59 |
60 | // Safari does not reliably fire the `pagehide` or `visibilitychange`
61 | // events when closing a tab, so we have to use `beforeunload` with a
62 | // timeout to check whether the default action was prevented.
63 | // - https://bugs.webkit.org/show_bug.cgi?id=151610
64 | // - https://bugs.webkit.org/show_bug.cgi?id=151234
65 | // NOTE: we only add this to Safari because adding it to Firefox would
66 | // prevent the page from being eligible for bfcache.
67 | if (isSafari_) {
68 | addEventListener('beforeunload', this.runTasksImmediately, true);
69 | }
70 | }
71 | }
72 |
73 | /**
74 | * @param {...*} args
75 | */
76 | pushTask(...args) {
77 | this.addTask_(Array.prototype.push, ...args);
78 | }
79 |
80 | /**
81 | * @param {...*} args
82 | */
83 | unshiftTask(...args) {
84 | this.addTask_(Array.prototype.unshift, ...args);
85 | }
86 |
87 | /**
88 | * Runs all scheduled tasks synchronously.
89 | */
90 | runTasksImmediately() {
91 | // By not passing a deadline, all tasks will be run sync.
92 | this.runTasks_();
93 | }
94 |
95 | /**
96 | * @return {boolean}
97 | */
98 | hasPendingTasks() {
99 | return this.taskQueue_.length > 0;
100 | }
101 |
102 |
103 | /**
104 | * Clears all pending tasks for the queue and stops any scheduled tasks
105 | * from running.
106 | */
107 | clearPendingTasks() {
108 | this.taskQueue_ = [];
109 | this.cancelScheduledRun_();
110 | }
111 |
112 | /**
113 | * Returns the state object for the currently running task. If no task is
114 | * running, null is returned.
115 | * @return {?Object}
116 | */
117 | getState() {
118 | return this.state_;
119 | }
120 |
121 | /**
122 | * Destroys the instance by unregistering all added event listeners and
123 | * removing any overridden methods.
124 | */
125 | destroy() {
126 | this.taskQueue_ = [];
127 | this.cancelScheduledRun_();
128 |
129 | if (this.ensureTasksRun_) {
130 | removeEventListener('visibilitychange', this.onVisibilityChange_, true);
131 |
132 | // Safari does not reliably fire the `pagehide` or `visibilitychange`
133 | // events when closing a tab, so we have to use `beforeunload` with a
134 | // timeout to check whether the default action was prevented.
135 | // - https://bugs.webkit.org/show_bug.cgi?id=151610
136 | // - https://bugs.webkit.org/show_bug.cgi?id=151234
137 | // NOTE: we only add this to Safari because adding it to Firefox would
138 | // prevent the page from being eligible for bfcache.
139 | if (isSafari_) {
140 | removeEventListener(
141 | 'beforeunload', this.runTasksImmediately, true);
142 | }
143 | }
144 | }
145 |
146 | /**
147 | * @param {!Function} arrayMethod Either the Array.prototype{push|shift}.
148 | * @param {!Function} task
149 | * @param {{minTaskTime: number}=} param1
150 | * @private
151 | */
152 | addTask_(arrayMethod, task, {minTaskTime = this.defaultMinTaskTime_} = {}) {
153 | const state = {
154 | time: now(),
155 | visibilityState: document.visibilityState,
156 | };
157 |
158 | arrayMethod.call(this.taskQueue_, {state, task, minTaskTime});
159 |
160 | this.scheduleTasksToRun_();
161 | }
162 |
163 | /**
164 | * Schedules the task queue to be processed. If the document is in the
165 | * hidden state, they queue is scheduled as a microtask so it can be run
166 | * in cases where a macrotask couldn't (like if the page is unloading). If
167 | * the document is in the visible state, `requestIdleCallback` is used.
168 | * @private
169 | */
170 | scheduleTasksToRun_() {
171 | if (this.ensureTasksRun_ && document.visibilityState === 'hidden') {
172 | queueMicrotask(this.runTasks_);
173 | } else {
174 | if (!this.idleCallbackHandle_) {
175 | this.idleCallbackHandle_ = rIC(this.runTasks_);
176 | }
177 | }
178 | }
179 |
180 | /**
181 | * Runs as many tasks in the queue as it can before reaching the
182 | * deadline. If no deadline is passed, it will run all tasks.
183 | * If an `IdleDeadline` object is passed (as is with `requestIdleCallback`)
184 | * then the tasks are run until there's no time remaining, at which point
185 | * we yield to input or other script and wait until the next idle time.
186 | * @param {IdleDeadline=} deadline
187 | * @private
188 | */
189 | runTasks_(deadline = undefined) {
190 | this.cancelScheduledRun_();
191 |
192 | if (!this.isProcessing_) {
193 | this.isProcessing_ = true;
194 |
195 | // Process tasks until there's no time left or we need to yield to input.
196 | while (this.hasPendingTasks() &&
197 | !shouldYield(deadline, this.taskQueue_[0].minTaskTime)) {
198 | const {task, state} = this.taskQueue_.shift();
199 |
200 | this.state_ = state;
201 | task(state);
202 | this.state_ = null;
203 | }
204 |
205 | this.isProcessing_ = false;
206 |
207 | if (this.hasPendingTasks()) {
208 | // Schedule the rest of the tasks for the next idle time.
209 | this.scheduleTasksToRun_();
210 | }
211 | }
212 | }
213 |
214 | /**
215 | * Cancels any scheduled idle callback and removes the handler (if set).
216 | * @private
217 | */
218 | cancelScheduledRun_() {
219 | cIC(this.idleCallbackHandle_);
220 | this.idleCallbackHandle_ = null;
221 | }
222 |
223 | /**
224 | * A callback for the `visibilitychange` event that runs all pending
225 | * callbacks immediately if the document's visibility state is hidden.
226 | * @private
227 | */
228 | onVisibilityChange_() {
229 | if (document.visibilityState === 'hidden') {
230 | this.runTasksImmediately();
231 | }
232 | }
233 | }
234 |
235 | /**
236 | * Returns true if the IdleDealine object exists and the remaining time is
237 | * less or equal to than the minTaskTime. Otherwise returns false.
238 | * @param {IdleDeadline|undefined} deadline
239 | * @param {number} minTaskTime
240 | * @return {boolean}
241 | * @private
242 | */
243 | const shouldYield = (deadline, minTaskTime) => {
244 | if (deadline && deadline.timeRemaining() <= minTaskTime) {
245 | return true;
246 | }
247 | return false;
248 | };
249 |
--------------------------------------------------------------------------------
/IdleValue.mjs:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | import {cIC, rIC} from './idle-callback-polyfills.mjs';
18 |
19 |
20 | /**
21 | * A class that wraps a value that is initialized when idle.
22 | */
23 | export class IdleValue {
24 | /**
25 | * Accepts a function to initialize the value of a variable when idle.
26 | * @param {!Function} init
27 | */
28 | constructor(init) {
29 | this.init_ = init;
30 |
31 | /** @type (?|undefined) */
32 | this.value_;
33 |
34 | this.idleHandle_ = rIC(() => {
35 | this.value_ = this.init_();
36 | });
37 | }
38 |
39 | /**
40 | * Returns the value if it's already been initialized. If it hasn't then the
41 | * initializer function is run immediately and the pending idle callback
42 | * is cancelled.
43 | * @return {?}
44 | */
45 | getValue() {
46 | if (this.value_ === undefined) {
47 | this.cancleIdleInit_();
48 | this.value_ = this.init_();
49 | }
50 | return this.value_;
51 | }
52 |
53 | /**
54 | * @param {?} newValue
55 | */
56 | setValue(newValue) {
57 | this.cancleIdleInit_();
58 | this.value_ = newValue;
59 | }
60 |
61 | /**
62 | * Cancels any scheduled requestIdleCallback and resets the handle.
63 | * @private
64 | */
65 | cancleIdleInit_() {
66 | if (this.idleHandle_) {
67 | cIC(this.idleHandle_);
68 | this.idleHandle_ = null;
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright 2018 Google, Inc.
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Idlize
2 |
3 | Helper classes and methods make it easier for developers to implement the [*idle-until-urgent*](https://philipwalton.com/articles/idle-until-urgent/) pattern and leverage the [`requestIdleCallback()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback) API.
4 |
5 | ## Installation
6 |
7 | You can install this library from npm by running:
8 |
9 | ```sh
10 | npm install idlize
11 | ```
12 |
13 | ## Usage
14 |
15 | This library is a collection of helper methods and classes (not a single bundle). As such, each helper should be imported separately. All public helpers are released at the level of the project, so they can be imported by directly referencing the helper's `.mjs` file.
16 |
17 | ```js
18 | import {defineIdleProperty} from 'idlize/defineIdleProperty.mjs'
19 | import {defineIdleProperties} from 'idlize/defineIdleProperties.mjs'
20 | import {cIC, rIC} from 'idlize/idle-callback-polyfills.mjs'
21 | import {IdleQueue} from 'idlize/IdleQueue.mjs'
22 | import {IdleValue} from 'idlize/IdleValue.mjs'
23 | ```
24 |
25 | Refer to each helper's [documentation](/docs) for examples and API usage details:
26 |
27 | - [`defineIdleProperty.mjs`](/docs/defineIdleProperty.md)
28 | - [`defineIdleProperties.mjs`](/docs/defineIdleProperties.md)
29 | - [`idle-callback-polyfills.mjs`](/docs/idle-callback-polyfills.md)
30 | - [`IdleQueue.mjs`](/docs/IdleQueue.md)
31 | - [`IdleValue.mjs`](/docs/IdleValue.md)
32 |
33 | ## Browser Support
34 |
35 |
36 |
37 |
38 |
39 | ✔
40 |
41 |
42 |
43 | ✔
44 |
45 |
46 |
47 | ✔
48 |
49 |
50 |
51 | ✔
52 |
53 |
54 |
55 | 9+
56 |
57 |
58 |
59 | ✔
60 |
61 |
62 |
63 |
64 | This code has been tested and known to work in all major browsers as well as Internet Explorer back to version 9.
65 |
66 | ## License
67 |
68 | [Apache 2.0](/LICENSE)
69 |
--------------------------------------------------------------------------------
/defineIdleProperties.mjs:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | import {defineIdleProperty} from './defineIdleProperty.mjs';
18 |
19 |
20 | /**
21 | * @param {!Object} obj The object to define the property on.
22 | * @param {!Object} props A mapping of property names to
23 | * initialization functions to be run idly.
24 | */
25 | export const defineIdleProperties = (obj, props) => {
26 | Object.keys(props).forEach((prop) => {
27 | defineIdleProperty(obj, prop, props[prop]);
28 | });
29 | };
30 |
--------------------------------------------------------------------------------
/defineIdleProperty.mjs:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | import {IdleValue} from './IdleValue.mjs';
18 |
19 |
20 | /**
21 | * @param {!Object} obj The object to define the property on.
22 | * @param {string} prop The property name.
23 | * @param {!Function} init An initialization function to by run idly.
24 | */
25 | export const defineIdleProperty = (obj, prop, init) => {
26 | const idleValue = new IdleValue(init);
27 |
28 | Object.defineProperty(obj, prop, {
29 | configurable: true,
30 | get: idleValue.getValue.bind(idleValue),
31 | set: idleValue.setValue.bind(idleValue),
32 | });
33 | };
34 |
--------------------------------------------------------------------------------
/docs/IdleQueue.md:
--------------------------------------------------------------------------------
1 | # `IdleQueue.mjs`
2 |
3 | [`idlize/IdleQueue.mjs`](/IdleQueue.mjs)
4 |
5 | ## Overview
6 |
7 | The `IdleQueue` class is a helper that allows developers to implement the [*idle-until-urgent*](https://philipwalton.com/articles/idle-until-urgent/) pattern in their code. It's useful for apps that want to split up their logic into a sequence of functions and schedule them to run idly.
8 |
9 | This class offers a few benefits over the regular usage of [`requestIdleCallback()`](https://developers.google.com/web/updates/2015/08/using-requestidlecallback):
10 |
11 | - The queue can be configured so all queued functions are guaranteed to run before the page is unloaded.
12 | - Queued tasks can be run immediately at any time.
13 | - Queued tasks can pass a minimum time budget, below which they won't attempt to run (this minimum time budget can also be configured per queue).
14 | - Queued tasks store the time/visibilityState when they were added to the queue, and are invoked with this data when run.
15 |
16 | ### Exports
17 |
18 | - [`IdleQueue`](#idlequeue)
19 |
20 | ### Usage
21 |
22 | ```js
23 | import {IdleQueue} from 'idlize/IdleQueue.mjs';
24 |
25 | const queue = new IdleQueue();
26 |
27 | queue.pushTask(() => {
28 | // Some expensive function that can run idly...
29 | });
30 |
31 | queue.pushTask(() => {
32 | // Some other task that depends on the above
33 | // expensive function having already run...
34 | });
35 | ```
36 |
37 | ## `IdleQueue`
38 |
39 | ### Methods
40 |
41 |
42 |
43 |
Name
44 |
Description
45 |
46 |
47 |
constructor(options)
48 |
49 |
Parameters:
50 |
51 |
52 | options.ensureTasksRun(boolean)
53 | Adds Page Lifecycle callbacks to ensure the queue is run before the user leaves the page (default: false).
54 |
55 |
56 | options.defaultMinTaskTime: (number)
57 | The default amount of idle time remaining in order for a task to be run (default: 0).
58 |
59 |
60 |
61 |
62 |
63 |
pushTask(task, options)
64 |
65 |
Parameters:
66 |
67 |
task: (function(Object))
68 | The task to add to the end of the queue.
69 |
70 |
options.minTaskTime: (number)
71 | The minimum amount of idle time remaining in order for a task to be run. If no value is passed, the queue default is used.
72 |
73 |
74 |
Adds a task to the end of the queue and schedules the queue to be run when next idle (if not already scheduled).
75 |
When the task is run, it's invoked with an object containing the following properties:
76 |
77 |
time: (number)
78 | The time (epoch time in milliseconds) when the task was added to the queue.
79 |
80 |
visibilityState: (string)
81 | The visibility state of the document when the task was added to the queue.
82 |
83 |
84 |
85 |
86 |
87 |
unshiftTask(task, options)
88 |
89 |
Parameters:
90 |
91 |
task: (function(Object<{{time: number, visibilityState: string}}>))
92 | The task to add to the beginning of the queue.
93 |
94 |
options.minTaskTime: (number)
95 | The minimum amount of idle time remaining in order for a task to be run. If no value is passed, the queue default is used.
96 |
97 |
98 |
Adds a task to the beginning of the queue and schedules the queue to be run when next idle (if not already scheduled).
99 |
When the task is run, it's invoked with an object containing the following properties:
100 |
101 |
time: (number)
102 | The time (epoch time in milliseconds) when the task was added to the queue.
103 |
104 |
visibilityState: (string)
105 | The visibility state of the document when the task was added to the queue.
106 |
107 |
108 |
109 |
110 |
111 |
runTasksImmediately()
112 |
113 |
Runs all queued tasks immediately (synchronously).
114 |
115 |
116 |
117 |
hasPendingTasks()
118 |
119 |
Returns:(boolean)
120 |
True if the queue has any tasks not yet run.
121 |
122 |
123 |
124 |
clearPendingTasks()
125 |
126 |
Unschedules all pending tasks in the queue.
127 |
128 |
129 |
130 |
getState()
131 |
132 |
Returns:(Object)
133 |
134 |
{time}: (number)
135 | The time (milliseconds, in epoch time) the task was added to the queue.
136 |
137 |
{visibilityState}: (string)
138 | The document's visibility state when the task was added to the queue.
139 |
140 |
141 |
142 |
143 |
144 |
--------------------------------------------------------------------------------
/docs/IdleValue.md:
--------------------------------------------------------------------------------
1 | # `IdleValue.mjs`
2 |
3 | [`idlize/IdleValue.mjs`](/IdleValue.mjs)
4 |
5 | ## Overview
6 |
7 | The `IdleValue` class is a helper that allows developers to implement the [*idle-until-urgent*](https://philipwalton.com/articles/idle-until-urgent/) pattern in their code. It's useful when you want to initialize a value during an idle period but ensure it can be initialized immediately as soon as it's needed.
8 |
9 | ### Exports
10 |
11 | - [`IdleValue`](#idlevalue)
12 |
13 | ### Usage
14 |
15 | ```js
16 | import {IdleValue} from 'idlize/IdleValue.mjs';
17 |
18 | class MyClass {
19 | constructor() {
20 | // Create an IdleValue instance for `this.data`. It's value is
21 | // initialized in an idle callback (or immediately as soon as
22 | // `this.data.getValue()` is called).
23 | this.data = new IdleValue(() => {
24 | // Run expensive code and return the result...
25 | });
26 | }
27 | }
28 | ```
29 |
30 | ## `IdleValue`
31 |
32 | ### Methods
33 |
34 |
35 |
36 |
Name
37 |
Description
38 |
39 |
40 |
constructor(init)
41 |
42 |
Parameters:
43 |
44 |
45 | init(Function)
46 | An initialization function (typically something expensive to compute) that returns a value.
47 |
48 |
49 |
The initialization function is scheduled to run in an idle callback as soon as the instance is created.
50 |
51 |
52 |
53 |
getValue()
54 |
55 |
Returns:(*)
56 |
Returns the value returned by the initialization function passed to the constructor. If the initialization function has already been run, the value is returned immediately. If the initialization function is still scheduled for an idle callback, that callback is cancelled, the initialization function is run synchronously, and the result is returned.
57 |
58 |
59 |
60 |
setValue(newValue)
61 |
62 |
Parameters:
63 |
64 |
65 | newValue(*)
66 |
67 |
68 |
Assigns a new value. If the initialization function passed to the constructor has not yet run, it is cancelled.
69 |
70 |
71 |
72 |
73 |
--------------------------------------------------------------------------------
/docs/defineIdleProperties.md:
--------------------------------------------------------------------------------
1 | # `defineIdleProperties.mjs`
2 |
3 | [`idlize/defineIdleProperties.mjs`](/defineIdleProperties.mjs)
4 |
5 | ## Overview
6 |
7 | This module provides a `defineIdleProperties` helper function that allows developers to implement the [*idle-until-urgent*](https://philipwalton.com/articles/idle-until-urgent/) pattern in their code. It's useful when you want to initialize one or more property values during an idle period but ensure they can be initialized immediately as soon as they're referenced.
8 |
9 | ### Exports
10 |
11 | - [`defineIdleProperties`](#defineidleproperties)
12 |
13 | ### Usage
14 |
15 | ```js
16 | import {defineIdleProperties} from 'idlize/defineIdleProperties.mjs';
17 |
18 | class MyClass {
19 | constructor() {
20 | // Define a getter for `this.data` whose value is initialized
21 | // in an idle callback (or immediately if referenced).
22 | defineIdleProperties(this, {
23 | data: () => {
24 | // Run expensive code and return the result...
25 | },
26 | });
27 | }
28 | }
29 | ```
30 |
31 | ## `defineIdleProperties`
32 |
33 | ### Syntax
34 |
35 | ```js
36 | defineIdleProperties(obj, props);
37 | ```
38 |
39 | ### Parameters
40 |
41 |
42 |
43 |
Name
44 |
Type
45 |
Description
46 |
47 |
48 |
obj
49 |
Object
50 |
51 | The object on which to define the property.
52 |
53 |
54 |
55 |
props
56 |
Object
57 |
58 | A dictionary of property names and initialization functions. See the defineIdleProperty documentation for prop and init.
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/docs/defineIdleProperty.md:
--------------------------------------------------------------------------------
1 | # `defineIdleProperty.mjs`
2 |
3 | [`idlize/defineIdleProperty.mjs`](/defineIdleProperty.mjs)
4 |
5 | ## Overview
6 |
7 | The module provides a `defineIdleProperty` helper function that allows developers to implement the [*idle-until-urgent*](https://philipwalton.com/articles/idle-until-urgent/) pattern in their code. It's useful when you want to initialize a property value during an idle period but ensure it can be initialized immediately as soon as it's referenced.
8 |
9 | ### Exports
10 |
11 | - [`defineIdleProperty`](#defineidleproperty)
12 |
13 | ### Usage
14 |
15 | ```js
16 | import {defineIdleProperty} from 'idlize/defineIdleProperty.mjs';
17 |
18 | class MyClass {
19 | constructor() {
20 | // Define a getter for `this.data` whose value is initialized
21 | // in an idle callback (or immediately if referenced).
22 | defineIdleProperty(this, 'data', () => {
23 | // Run expensive code and return the result...
24 | });
25 | }
26 | }
27 | ```
28 |
29 | ## `defineIdleProperty`
30 |
31 | ### Syntax
32 |
33 | ```js
34 | defineIdleProperty(obj, prop, init);
35 | ```
36 |
37 | ### Parameters
38 |
39 |
40 |
41 |
Name
42 |
Type
43 |
Description
44 |
45 |
46 |
obj
47 |
Object
48 |
49 | The object on which to define the property.
50 |
51 |
52 |
53 |
prop
54 |
string
55 |
56 | The name of the property.
57 |
58 |
59 |
60 |
init
61 |
Function
62 |
63 | An function (typically something expensive to compute) that returns a value. The function is scheduled to run in an idle callback as soon as the property is defined. If the property is referenced before the function can be run in an idle callback, the idle callback is canceled, the function is run immediately, and the return value of the function is set as the value of the property.
64 |