最近的回复显示需要2秒

有没有办法立即显示最新的回复?目前,我使用这段代码:

  api.onPageChange(() => {
    if (window.location.pathname === "/") {
      const container = document.querySelector(".latest-topic-list");
      if (!container || container.dataset.modified === "true") return;

      fetch("/posts.json?order=created")
        .then(res => res.json())
        .then(data => {
          const replies = data.latest_posts
            .filter(p => p.post_number > 1 && !p.topic_slug.includes("private-message"))
            .slice(0, 15);

          const topicFetches = replies.map(post =>
            fetch(`/t/${post.topic_id}.json`)
              .then(res => res.json())
              .then(topic => {
                return {
                  post,
                  category: topic.category_id ? topic.category_name : null,
                  tags: topic.tags || []
                };
              })
          );

          Promise.all(topicFetches).then(results => {
            const rows = results.map(({ post, category, tags }) => {
              const url = `/t/${post.topic_slug}/${post.topic_id}/${post.post_number}`;
              const avatarUrl = post.avatar_template.replace("{size}", "45");
              const excerpt = post.excerpt?.replace(/<\/?[^\s>]+(\>|$)/g, "")?.slice(0, 120) + (post.excerpt?.length > 120 ? '...' : '') || '';

              const categoryHtml = category
                ? `<span style="font-size: 0.85em; color: #666;">Categoria: <strong>${category}</strong></span><br>`
                : '';

              const tagsHtml = tags.length
                ? `<span style="font-size: 0.85em; color: #666;">Tags: ${tags.map(tag => `<span style="background:#eee; padding:2px 6px; border-radius:3px; margin-right:4px;">${tag}</span>`).join("")}</span>`
                : '';

              return `
                <tr class="topic-list-item">
                  <td class="main-link clearfix">
                    <div style="display: flex; align-items: center; gap: 16px; padding: 8px 0;">
                      <div style="flex-shrink: 0;">
                        <a class="avatar-link" href="/u/${post.username}">
                          <img loading="lazy" width="45" height="45" src="${avatarUrl}" class="avatar" alt="${post.username}">
                        </a>
                      </div>
                      <div style="display: flex; flex-direction: column; justify-content: center; padding-top: 8px; padding-bottom: 8px;">
                        <span class="link-top-line" style="margin-bottom: 6px;">
                          <a href="${url}" class="title raw-link">${excerpt}</a>
                        </span>
                        <div class="link-bottom-line">
                          ${categoryHtml}
                          ${tagsHtml}
                        </div>
                      </div>
                    </div>
                  </td>
                </tr>
              `;
            }).join("");

            // Cria o container da seção de últimos comentários
            const latestRepliesContainer = document.createElement("div");
            latestRepliesContainer.className = "latest-replies-container";
            latestRepliesContainer.style.marginTop = "2em";

            latestRepliesContainer.innerHTML = `
              <table class="topic-list latest-topic-list">
                <thead>
                  <tr>
                    <th class="default">Últimos Comentários</th>
                  </tr>
                </thead>
                <tbody>
                  ${rows}
                </tbody>
              </table>
            `;

            container.parentNode.insertBefore(latestRepliesContainer, container.nextSibling);
            container.dataset.modified = "true";
          });
        })
        .catch(error => {
          console.error("Erro ao buscar últimos comentários:", error);
        });
    }
  });
/script```

但内容平均需要 2 秒钟才会出现。带有“最新评论”的右侧边栏块也是如此。这正常吗?

[引述=“David_Ghost, post:1, topic:365041”]
目前,我使用这段代码
[/引述]

你为什么要添加任何代码?

它可以开箱即用,没有任何特殊情况;对你来说是不是坏了?

这就是他的问题。

我认为这是可以预期的,因为代码进行了多次 API 请求。
它检索最新的帖子,然后为每个主题 ID(此处为 15 个)发出一个请求以检索类别名称。

目前,我不知道除了使用插件和进行自定义 SQL 查询之外,还有没有其他方法。

完全正确。
但是右侧边栏区块也会发出请求吗?它给我的最近回复结果一样。需要 2 秒才能出现。

我将看看如何制作一个插件。谢谢。

是的,它在检索最新的帖子方面做得一样,但仅此而已。它不会尝试获取类别名称,这就是区别。

我明白了。谢谢你的帮助。

我会尝试寻找其他解决方案

最后,我目前使用的是这个:

<script type="text/discourse-plugin" version="0.11.3">
  api.onPageChange(() => {
    if (window.location.pathname === "/") {
      const container = document.querySelector(".latest-topic-list");
      if (!container) return;
      
      // 避免多次初始化
      if (window.latestRepliesInitialized) return;
      window.latestRepliesInitialized = true;
      
      // 配置
      const POLLING_INTERVAL = 2000; // 2 秒
      const COMMENTS_TO_SHOW = 15;
      const CACHE_DURATION = 30 * 60 * 1000; // 30 分钟
      
      // 缓存键
      const CACHE_KEY = "discourse_latest_replies_data";
      const CACHE_TIMESTAMP_KEY = "discourse_latest_replies_timestamp";
      const CACHE_LAST_ID_KEY = "discourse_latest_replies_last_id";
      
      // 存储最后看到的帖子 ID 以进行比较
      let lastSeenPostId = parseInt(localStorage.getItem(CACHE_LAST_ID_KEY) || "0");
      let pollingIntervalId = null;
      
      console.log(`正在初始化最新评论插件(缓存中的最后 ID:${lastSeenPostId})`);
      
      // 加载评论的函数
      function loadLatestReplies(silent = false, forceRefresh = false) {
        // 如果不是强制刷新,先检查缓存
        if (!forceRefresh) {
          const cachedData = localStorage.getItem(CACHE_KEY);
          const cacheTimestamp = localStorage.getItem(CACHE_TIMESTAMP_KEY);
          const now = Date.now();
          
          // 如果我们有有效的缓存数据
          if (cachedData && cacheTimestamp && now - parseInt(cacheTimestamp) < CACHE_DURATION) {
            try {
              const results = JSON.parse(cachedData);
              console.log(`使用缓存数据(${results.length} 条评论,缓存于 ${Math.round((now - parseInt(cacheTimestamp)) / 1000 / 60)} 分钟前)`);
              renderLatestReplies(results, false);
              
              // 如果不是静默模式,无需执行其他操作
              if (!silent) {
                return;
              }
              
              // 如果是静默模式,继续检查更新
            } catch (e) {
              console.error("处理缓存时出错:", e);
              // 如果缓存出错,继续获取新鲜数据
            }
          } else if (cachedData) {
            console.log("缓存已过期,获取新鲜数据");
          } else {
            console.log("未找到缓存,获取新鲜数据");
          }
        } else {
          console.log("强制刷新,忽略缓存");
        }
        
        // 如果不是静默模式,显示加载指示器
        if (!silent) {
          // 如果已存在评论容器,则不显示指示器
          const existingContainer = document.querySelector(".latest-replies-container");
          if (!existingContainer) {
            let loadingIndicator = document.getElementById("latest-replies-loading");
            if (!loadingIndicator) {
              loadingIndicator = document.createElement("div");
              loadingIndicator.id = "latest-replies-loading";
              loadingIndicator.innerHTML = `
                <div style="text-align: center; padding: 20px;">
                  <span class="spinner small"></span>
                  <span style="margin-left: 10px;">正在加载最新评论...</span>
                </div>
              `;
              container.parentNode.insertBefore(loadingIndicator, container.nextSibling);
            }
          }
        }
        
        // 获取最新数据
        fetch("/posts.json?order=created")
          .then(res => res.json())
          .then(data => {
            // 诊断日志
            if (!silent) {
              console.log("从 API 接收到的数据:", data.latest_posts.length);
            }
            
            const replies = data.latest_posts
              .filter(p => p.post_number > 1 && !p.topic_slug.includes("private-message"))
              .slice(0, COMMENTS_TO_SHOW);
            
            // 检查是否有新帖子
            const maxId = replies.length > 0 ? Math.max(...replies.map(post => post.id)) : 0;
            const hasNewPosts = maxId > lastSeenPostId;
            
            // 诊断日志
            if (hasNewPosts && !silent) {
              console.log(`检测到新帖子。最后 ID: ${lastSeenPostId}, 新最大 ID: ${maxId}`);
            }
            
            // 更新最后看到的 ID
            if (maxId > lastSeenPostId) {
              lastSeenPostId = maxId;
              localStorage.setItem(CACHE_LAST_ID_KEY, lastSeenPostId.toString());
            }
            
            // 如果没有新帖子且是静默检查,且不强制刷新,则不执行任何操作
            if (!hasNewPosts && silent && !forceRefresh) {
              return;
            }
            
            // 获取主题详情
            const topicPromises = replies.map(post => {
              // 检查是否有缓存的主题
              const topicCacheKey = `discourse_topic_${post.topic_id}`;
              const cachedTopic = localStorage.getItem(topicCacheKey);
              
              if (cachedTopic && !forceRefresh) {
                try {
                  return Promise.resolve(JSON.parse(cachedTopic));
                } catch (e) {
                  console.error(`处理主题 ${post.topic_id} 的缓存时出错:`, e);
                  // 如果缓存出错,从服务器获取
                }
              }
              
              return fetch(`/t/${post.topic_id}.json`)
                .then(res => res.json())
                .then(topic => {
                  // 将主题存入缓存
                  localStorage.setItem(topicCacheKey, JSON.stringify(topic));
                  return topic;
                })
                .catch(error => {
                  console.error(`获取主题 ${post.topic_id} 时出错:`, error);
                  return { category_id: null, category_name: null, tags: [] };
                });
            });
            
            Promise.all(topicPromises)
              .then(topics => {
                const results = replies.map((post, index) => {
                  const topic = topics[index];
                  return {
                    post,
                    category: topic.category_id ? topic.category_name : null,
                    tags: topic.tags || []
                  };
                });
                
                // 将结果存入缓存
                localStorage.setItem(CACHE_KEY, JSON.stringify(results));
                localStorage.setItem(CACHE_TIMESTAMP_KEY, Date.now().toString());
                
                // 渲染结果
                renderLatestReplies(results, hasNewPosts || forceRefresh);
              })
              .catch(error => {
                console.error("处理主题时出错:", error);
              });
          })
          .catch(error => {
            console.error("获取最新评论时出错:", error);
            // 如果出错,移除加载指示器
            if (!silent) {
              const loadingElement = document.getElementById("latest-replies-loading");
              if (loadingElement) loadingElement.remove();
            }
          });
      }
      
      // 渲染结果的函数
      function renderLatestReplies(results, animate = false) {
        // 移除加载指示器
        const loadingElement = document.getElementById("latest-replies-loading");
        if (loadingElement) loadingElement.remove();
        
        // 如果没有结果,不执行任何操作
        if (!results || results.length === 0) {
          console.log("未找到要显示的评论");
          return;
        }
        
        const rows = results.map(({ post, category, tags }) => {
          const url = `/t/${post.topic_slug}/${post.topic_id}/${post.post_number}`;
          const avatarUrl = post.avatar_template.replace("{size}", "45");
          const excerpt = post.excerpt?.replace(/</?[^>]+(>|$)/g, "")?.slice(0, 120) + (post.excerpt?.length > 120 ? '...' : '') || '';

          const categoryHtml = category
            ? `<span style="font-size: 0.85em; color: #666;">分类:<strong>${category}</strong></span><br>`
            : '';

          const tagsHtml = tags.length
            ? `<span style="font-size: 0.85em; color: #666;">标签: ${tags.map(tag => `<span style="background:#eee; padding:2px 6px; border-radius:3px; margin-right:4px;">${tag}</span>`).join("")}</span>`
            : '';

          const animationClass = animate ? 'new-comment' : '';

          return `
            <tr class="topic-list-item ${animationClass}" data-post-id="${post.id}">
              <td class="main-link clearfix">
                <div style="display: flex; align-items: center; gap: 16px; padding: 8px 0;">
                  <div style="flex-shrink: 0;">
                    <a class="avatar-link" href="/u/${post.username}">
                      <img loading="lazy" width="45" height="45" src="${avatarUrl}" class="avatar" alt="${post.username}">
                    </a>
                  </div>
                  <div style="display: flex; flex-direction: column; justify-content: center; padding-top: 8px; padding-bottom: 8px;">
                    <span class="link-top-line" style="margin-bottom: 6px;">
                      <a href="${url}" class="title raw-link">${excerpt}</a>
                    </span>
                    <div class="link-bottom-line">
                      ${categoryHtml}
                      ${tagsHtml}
                    </div>
                  </div>
                </div>
              </td>
            </tr>
          `;
        }).join("");

        // 如果尚未添加,则添加动画样式
        if (!document.getElementById('latest-replies-style')) {
          const style = document.createElement('style');
          style.id = 'latest-replies-style';
          style.textContent = `
            @keyframes highlightNew {
              0% { background-color: rgba(255, 255, 0, 0.3); }
              100% { background-color: transparent; }
            }
            .new-comment {
              animation: highlightNew 2s ease-out;
            }
          `;
          document.head.appendChild(style);
        }

        // 如果存在,移除现有容器
        const existingContainer = document.querySelector(".latest-replies-container");
        if (existingContainer) {
          existingContainer.remove();
        }

        // 创建最新评论部分的容器
        const latestRepliesContainer = document.createElement("div");
        latestRepliesContainer.className = "latest-replies-container";
        latestRepliesContainer.style.marginTop = "2em";

        // 添加手动刷新按钮和状态指示器
        const cacheTime = new Date(parseInt(localStorage.getItem(CACHE_TIMESTAMP_KEY) || Date.now()));
        const formattedTime = cacheTime.toLocaleTimeString();
        
        latestRepliesContainer.innerHTML = `
          <table class="topic-list latest-topic-list">
            <thead>
              <tr>
                <th class="default">
                  最新评论
                  <span id="comments-status" style="font-size: 0.8em; font-weight: normal; margin-left: 10px;">
                  </span>
                  <button id="refresh-comments" class="btn btn-flat no-text btn-icon" style="float: right;" title="刷新评论">
                    <svg class="fa d-icon d-icon-sync svg-icon svg-string" width="16" height="16" aria-hidden="true"><use xlink:href="#sync"></use></svg>
                  </button>
                </th>
              </tr>
            </thead>
            <tbody id="latest-replies-tbody">
              ${rows}
            </tbody>
          </table>
        `;

        container.parentNode.insertBefore(latestRepliesContainer, container.nextSibling);
        container.dataset.modified = "true";
        
        // 为刷新按钮添加点击事件
        document.getElementById("refresh-comments").addEventListener("click", function() {
          // 更新状态文本
          const statusElement = document.getElementById("comments-status");
          if (statusElement) {
            statusElement.textContent = "(正在更新...)";
          }
          
          // 强制刷新
          loadLatestReplies(false, true);
        });
        
        console.log(`已渲染 ${results.length} 条评论`);
      }
      
      // 启动初始加载(使用缓存)
      loadLatestReplies(false, false);
      
      // 配置高频轮询
      pollingIntervalId = setInterval(() => {
        // 仅当用户在主页时更新
        if (window.location.pathname === "/") {
          loadLatestReplies(true, false); // 静默模式,如有缓存则使用
        }
      }, POLLING_INTERVAL);
      
      console.log(`轮询已设置为每 ${POLLING_INTERVAL}ms 执行一次`);
      
      // 当用户离开页面时清除间隔
      api.onPageChange((url) => {
        if (url !== "/") {
          console.log("正在离开主页,清理资源");
          
          if (pollingIntervalId) {
            clearInterval(pollingIntervalId);
            pollingIntervalId = null;
          }
          
          window.latestRepliesInitialized = false;
        }
      });
    }
  });
</script>

它按预期工作。它会自动添加新评论,然后将其加入缓存。我知道这不是最理想的方案。我很快就会尝试开发一个插件。

这里的目标是:与其使用具有“最新主题”页面样式的分类,我更希望有一个具有“最新回复”样式的分类。