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/122963/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 tick;
  52. }
  53. /**
  54. * @param regex - should match the site you're waiting for
  55. * @param action - the callback that will be executed when a matching url is visited
  56. * @param stopLooking - if true the function will stop waiting for another url match after the first match
  57. */
  58. function waitForUrl(regex, action, stopLooking) {
  59. function checkUrl(urlTest) {
  60. var url = window.location.href;
  61. if(url !== lastUrl && urlTest(url)) {
  62. if(stopLooking) {
  63. clearInterval(tick);
  64. }
  65. lastUrl = url;
  66. action();
  67. }
  68. lastUrl = url;
  69. }
  70. var urlTest = (typeof regex === 'function' ? regex : regex.test.bind(regex)),
  71. tick = setInterval(checkUrl.bind(null, urlTest), 300),
  72. lastUrl;
  73. checkUrl(urlTest);
  74. return tick;
  75. }