Wait For Elements

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

当前为 2014-12-18 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/5679/28654/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 id = 'fke' + Math.floor(Math.random() * 12345);
  8. function findElem(sel) {
  9. var found = [].filter.call(document.querySelectorAll(sel), function(elem) {
  10. return elem.dataset[id] !== 'y';
  11. });
  12. if(found.length > 0) {
  13. found.forEach(function(elem) {
  14. elem.dataset[id] = 'y';
  15. action(elem);
  16. });
  17. if(stopLooking) {
  18. clearInterval(tick);
  19. }
  20. }
  21. }
  22. var tick = setInterval(findElem.bind(null, sel), 300);
  23. findElem(sel);
  24. return tick;
  25. }
  26. /**
  27. * @param regex - should match the site you're waiting for
  28. * @param action - the callback that will be executed when a matching url is visited
  29. * @param stopLooking - if true the function will stop waiting for another url match after the first match
  30. */
  31. function waitForUrl(regex, action, stopLooking) {
  32. function checkUrl(regex) {
  33. var url = window.location.href;
  34. if(url !== lastUrl && regex.test(url)) {
  35. lastUrl = url;
  36. action();
  37. }
  38. if(stopLooking) {
  39. clearInterval(tick);
  40. }
  41. lastUrl = url;
  42. }
  43. var tick = setInterval(checkUrl.bind(null, regex), 300),
  44. lastUrl;
  45. checkUrl(regex);
  46. return tick;
  47. }