Wait For Elements

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

当前为 2014-10-22 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/5679/22195/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. }
  25. /**
  26. * @param regex - should match the site you're waiting for
  27. * @param action - the callback that will be executed when a matching url is visited
  28. * @param stopLooking - if true the function will stop waiting for another url match after the first match
  29. */
  30. function waitForUrl(regex, action, stopLooking) {
  31. function checkUrl(regex) {
  32. var url = window.location.href;
  33. if(url !== lastUrl && regex.test(url)) {
  34. action();
  35. }
  36. if(stopLooking) {
  37. clearInterval(tick);
  38. }
  39. lastUrl = url;
  40. }
  41. var tick = setInterval(checkUrl.bind(null, regex), 300),
  42. lastUrl;
  43. checkUrl(regex);
  44. }