infiniteScroll.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // @license http://www.gnu.org/licenses/agpl-3.0.html AGPL-3.0
  2. function insertBeforeLast(node, elem) {
  3. node.insertBefore(elem, node.childNodes[node.childNodes.length - 2]);
  4. }
  5. function getLoadMore(doc) {
  6. return doc.querySelector('.show-more:not(.timeline-item)');
  7. }
  8. function isDuplicate(item, itemClass) {
  9. const tweet = item.querySelector(".tweet-link");
  10. if (tweet == null) return false;
  11. const href = tweet.getAttribute("href");
  12. return document.querySelector(itemClass + " .tweet-link[href='" + href + "']") != null;
  13. }
  14. window.onload = function() {
  15. const url = window.location.pathname;
  16. const isTweet = url.indexOf("/status/") !== -1;
  17. const containerClass = isTweet ? ".replies" : ".timeline";
  18. const itemClass = containerClass + ' > div:not(.top-ref)';
  19. var html = document.querySelector("html");
  20. var container = document.querySelector(containerClass);
  21. var loading = false;
  22. window.addEventListener('scroll', function() {
  23. if (loading) return;
  24. if (html.scrollTop + html.clientHeight >= html.scrollHeight - 3000) {
  25. loading = true;
  26. var loadMore = getLoadMore(document);
  27. if (loadMore == null) return;
  28. loadMore.children[0].text = "Loading...";
  29. var url = new URL(loadMore.children[0].href);
  30. url.searchParams.append('scroll', 'true');
  31. fetch(url.toString()).then(function (response) {
  32. return response.text();
  33. }).then(function (html) {
  34. var parser = new DOMParser();
  35. var doc = parser.parseFromString(html, 'text/html');
  36. loadMore.remove();
  37. for (var item of doc.querySelectorAll(itemClass)) {
  38. if (item.className == "timeline-item show-more") continue;
  39. if (isDuplicate(item, itemClass)) continue;
  40. if (isTweet) container.appendChild(item);
  41. else insertBeforeLast(container, item);
  42. }
  43. loading = false;
  44. const newLoadMore = getLoadMore(doc);
  45. if (newLoadMore == null) return;
  46. if (isTweet) container.appendChild(newLoadMore);
  47. else insertBeforeLast(container, newLoadMore);
  48. }).catch(function (err) {
  49. console.warn('Something went wrong.', err);
  50. loading = true;
  51. });
  52. }
  53. });
  54. };
  55. // @license-end