schedule.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use strict";
  2. var util = require("./util");
  3. var schedule;
  4. var noAsyncScheduler = function() {
  5. throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  6. };
  7. var NativePromise = util.getNativePromise();
  8. if (util.isNode && typeof MutationObserver === "undefined") {
  9. var GlobalSetImmediate = global.setImmediate;
  10. var ProcessNextTick = process.nextTick;
  11. schedule = util.isRecentNode
  12. ? function(fn) { GlobalSetImmediate.call(global, fn); }
  13. : function(fn) { ProcessNextTick.call(process, fn); };
  14. } else if (typeof NativePromise === "function" &&
  15. typeof NativePromise.resolve === "function") {
  16. var nativePromise = NativePromise.resolve();
  17. schedule = function(fn) {
  18. nativePromise.then(fn);
  19. };
  20. } else if ((typeof MutationObserver !== "undefined") &&
  21. !(typeof window !== "undefined" &&
  22. window.navigator &&
  23. (window.navigator.standalone || window.cordova))) {
  24. schedule = (function() {
  25. var div = document.createElement("div");
  26. var opts = {attributes: true};
  27. var toggleScheduled = false;
  28. var div2 = document.createElement("div");
  29. var o2 = new MutationObserver(function() {
  30. div.classList.toggle("foo");
  31. toggleScheduled = false;
  32. });
  33. o2.observe(div2, opts);
  34. var scheduleToggle = function() {
  35. if (toggleScheduled) return;
  36. toggleScheduled = true;
  37. div2.classList.toggle("foo");
  38. };
  39. return function schedule(fn) {
  40. var o = new MutationObserver(function() {
  41. o.disconnect();
  42. fn();
  43. });
  44. o.observe(div, opts);
  45. scheduleToggle();
  46. };
  47. })();
  48. } else if (typeof setImmediate !== "undefined") {
  49. schedule = function (fn) {
  50. setImmediate(fn);
  51. };
  52. } else if (typeof setTimeout !== "undefined") {
  53. schedule = function (fn) {
  54. setTimeout(fn, 0);
  55. };
  56. } else {
  57. schedule = noAsyncScheduler;
  58. }
  59. module.exports = schedule;