Wait For Elements

given a selector waits for elements to be inserted into the DOM and executes a callback for each match

当前为 2016-05-01 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/5679/122976/Wait%20For%20Elements.js

  1. /**
  2. * @param sel - the selector you want to wait for
  3. * @param action - the callback that will be executed when element/s matching the given selector are found, it is passed the array of found elements
  4. * @param stopLooking - if true the function will stop looking for more elements after the first match
  5. */
  6. function waitForElems(sel, action, stopLooking) {
  7. var tick;
  8. var id = 'fke' + Math.floor(Math.random() * 12345);
  9. var type = window.MutationObserver ? 'M' : 'S';
  10. var lastMutation = Date.now();
  11. var lastCall = Date.now();
  12. var queuedCall;
  13. function throttle(func) {
  14. var now = Date.now();
  15. clearTimeout(queuedCall);
  16. // less than 100ms since last mutation
  17. if(now - lastMutation < 100) {
  18. // 500ms or more since last query
  19. if(now - lastCall >= 500) {
  20. func();
  21. } else {
  22. queuedCall = setTimeout(func, 100);
  23. }
  24. } else {
  25. func();
  26. }
  27. lastMutation = now;
  28. }
  29. function findElem(sel) {
  30. lastCall = Date.now();
  31. var found = [].filter.call(document.querySelectorAll(sel), function(elem) {
  32. return elem.dataset[id] !== 'y';
  33. });
  34. if(found.length > 0) {
  35. if(stopLooking) {
  36. type === 'M' ? tick.disconnect() : clearInterval(tick);
  37. }
  38. found.forEach(function(elem) {
  39. elem.dataset[id] = 'y';
  40. action(elem);
  41. });
  42. }
  43. }
  44. if(type === 'M') {
  45. tick = new MutationObserver(throttle.bind(null, findElem.bind(null, sel)));
  46. tick.observe(document.body, { subtree: true, childList: true });
  47. } else {
  48. tick = setInterval(findElem.bind(null, sel), 300);
  49. }
  50. findElem(sel);
  51. return {
  52. type: type,
  53. stop: function() {
  54. if(type === 'M') {
  55. tick.disconnect();
  56. } else {
  57. clearInterval(tick);
  58. }
  59. }
  60. };
  61. }
  62. /**
  63. * @param regex - should match the site you're waiting for
  64. * @param action - the callback that will be executed when a matching url is visited
  65. * @param stopLooking - if true the function will stop waiting for another url match after the first match
  66. */
  67. function waitForUrl(regex, action, stopLooking) {
  68. function checkUrl(urlTest) {
  69. var url = window.location.href;
  70. if(url !== lastUrl && urlTest(url)) {
  71. if(stopLooking) {
  72. clearInterval(tick);
  73. }
  74. lastUrl = url;
  75. action();
  76. }
  77. lastUrl = url;
  78. }
  79. var urlTest = (typeof regex === 'function' ? regex : regex.test.bind(regex)),
  80. tick = setInterval(checkUrl.bind(null, urlTest), 300),
  81. lastUrl;
  82. checkUrl(urlTest);
  83. return tick;
  84. }