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