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/122961/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. Util.log(now - lastCall);
  20. if(now - lastCall >= 500) {
  21. func();
  22. } else {
  23. queuedCall = setTimeout(func, 100);
  24. }
  25. } else {
  26. func();
  27. }
  28. lastMutation = now;
  29. }
  30. function findElem(sel) {
  31. lastCall = Date.now();
  32. var found = [].filter.call(document.querySelectorAll(sel), function(elem) {
  33. return elem.dataset[id] !== 'y';
  34. });
  35. if(found.length > 0) {
  36. if(stopLooking) {
  37. type === 'M' ? tick.disconnect() : clearInterval(tick);
  38. }
  39. found.forEach(function(elem) {
  40. elem.dataset[id] = 'y';
  41. action(elem);
  42. });
  43. }
  44. }
  45. if(type === 'M') {
  46. tick = new MutationObserver(throttle.bind(null, findElem.bind(null, sel)));
  47. tick.observe(document.body, { subtree: true, childList: true });
  48. } else {
  49. tick = setInterval(findElem.bind(null, sel), 300);
  50. }
  51. findElem(sel);
  52. return tick;
  53. }
  54. /**
  55. * @param regex - should match the site you're waiting for
  56. * @param action - the callback that will be executed when a matching url is visited
  57. * @param stopLooking - if true the function will stop waiting for another url match after the first match
  58. */
  59. function waitForUrl(regex, action, stopLooking) {
  60. function checkUrl(urlTest) {
  61. var url = window.location.href;
  62. if(url !== lastUrl && urlTest(url)) {
  63. if(stopLooking) {
  64. clearInterval(tick);
  65. }
  66. lastUrl = url;
  67. action();
  68. }
  69. lastUrl = url;
  70. }
  71. var urlTest = (typeof regex === 'function' ? regex : regex.test.bind(regex)),
  72. tick = setInterval(checkUrl.bind(null, urlTest), 300),
  73. lastUrl;
  74. checkUrl(urlTest);
  75. return tick;
  76. }