2
0
فهرست منبع

✨ feat(progress): improve loading progress tracking accuracy

- optimize resource count estimation algorithm with more conservative buffer strategy
- implement dynamic weight adjustment between server and client progress
- add completion detection mechanism based on resource loading inactivity
- refine total progress calculation with completion bonus for near-finished state
- adjust resource completion buffer from 5 to 3 to prevent overestimation
- remove dynamic import monitoring to reduce unnecessary overhead
- add last resource loading time tracking for better completion detection
- optimize progress update logic with more accurate percentage calculation
yourname 7 ماه پیش
والد
کامیت
7c1686c034
1فایلهای تغییر یافته به همراه74 افزوده شده و 54 حذف شده
  1. 74 54
      vite-plugin-compile-progress.js

+ 74 - 54
vite-plugin-compile-progress.js

@@ -97,59 +97,97 @@ export function progressTrackingPlugin() {
                   let resourcesCompleted = 0;  
                   let resourcesCompleted = 0;  
                   let estimatedTotal = 0;  
                   let estimatedTotal = 0;  
                   let isLoading = true;  
                   let isLoading = true;  
+                  let completionTimer = null;  
+                  let lastResourceTime = Date.now();  
   
   
                   // DOM 元素引用  
                   // DOM 元素引用  
                   const progressBar = document.getElementById('vite-progress-bar');  
                   const progressBar = document.getElementById('vite-progress-bar');  
                   const statusDisplay = document.getElementById('vite-progress-status');  
                   const statusDisplay = document.getElementById('vite-progress-status');  
   
   
-                  // 预估资源总数  
+                  // 改进的预估算法  
                   function estimateResourceCount() {  
                   function estimateResourceCount() {  
                     const scripts = document.querySelectorAll('script[src]').length;  
                     const scripts = document.querySelectorAll('script[src]').length;  
                     const links = document.querySelectorAll('link[href]').length;  
                     const links = document.querySelectorAll('link[href]').length;  
                     const styleSheets = document.querySelectorAll('link[rel="stylesheet"]').length;  
                     const styleSheets = document.querySelectorAll('link[rel="stylesheet"]').length;  
                     const preloadLinks = document.querySelectorAll('link[rel="preload"], link[rel="modulepreload"]').length;  
                     const preloadLinks = document.querySelectorAll('link[rel="preload"], link[rel="modulepreload"]').length;  
                       
                       
-                    // 基于现有资源数量和经验值估算  
+                    // 更保守的预估,避免过度增长  
                     const baseEstimate = scripts + links + styleSheets + preloadLinks;  
                     const baseEstimate = scripts + links + styleSheets + preloadLinks;  
-                    const dynamicEstimate = Math.max(baseEstimate * 1.5, 10); // 至少10个资源  
+                    const conservativeEstimate = Math.max(baseEstimate + 10, 15); // 只加10个缓冲  
                       
                       
-                    return Math.floor(dynamicEstimate);  
+                    return conservativeEstimate;  
+                  }  
+  
+                  // 检测是否完成加载  
+                  function checkCompletion() {  
+                    const now = Date.now();  
+                    const timeSinceLastResource = now - lastResourceTime;  
+                      
+                    // 如果2秒内没有新资源加载,且服务端完成,认为加载完成  
+                    if (serverProgress >= 1.0 && timeSinceLastResource > 2000) {  
+                      console.log('Loading appears to be complete - no new resources for 2 seconds');  
+                      forceComplete();  
+                      return;  
+                    }  
+                      
+                    // 如果进度超过98%且3秒内没有新资源,强制完成  
+                    if (serverProgress >= 1.0 && resourcesCompleted >= estimatedTotal * 0.9 && timeSinceLastResource > 3000) {  
+                      console.log('Force completing - high progress with no recent activity');  
+                      forceComplete();  
+                      return;  
+                    }  
+                  }  
+  
+                  // 强制完成  
+                  function forceComplete() {  
+                    if (!isLoading) return;  
+                      
+                    isLoading = false;  
+                    progressBar.style.width = '100%';  
+                    statusDisplay.style.display = 'none';  
+                    progressBar.classList.add('complete');  
+                      
+                    console.log('Loading completed!');  
+                      
+                    setTimeout(() => {  
+                      progressBar.style.display = 'none';  
+                    }, 1000);  
                   }  
                   }  
   
   
                   // 更新进度条和状态显示  
                   // 更新进度条和状态显示  
                   function updateProgress() {  
                   function updateProgress() {  
-                    if (!progressBar || !statusDisplay) return;  
+                    if (!progressBar || !statusDisplay || !isLoading) return;  
   
   
-                    // 服务端进度权重70%,客户端资源进度权重30%  
-                    const serverWeight = 0.7;  
-                    const clientWeight = 0.3;  
+                    // 动态调整权重:服务端完成后,客户端权重增加  
+                    const serverWeight = serverProgress < 1.0 ? 0.6 : 0.3;  
+                    const clientWeight = serverProgress < 1.0 ? 0.4 : 0.7;  
                       
                       
                     const serverPart = serverProgress * serverWeight;  
                     const serverPart = serverProgress * serverWeight;  
                     const clientPart = estimatedTotal > 0 ?   
                     const clientPart = estimatedTotal > 0 ?   
-                      (resourcesCompleted / estimatedTotal) * clientWeight : 0;  
+                      Math.min(resourcesCompleted / estimatedTotal, 1.0) * clientWeight : 0;  
                       
                       
-                    const totalProgress = Math.min((serverPart + clientPart) * 100, 100);  
+                    let totalProgress = Math.min((serverPart + clientPart) * 100, 100);  
+                      
+                    // 如果服务端完成且客户端接近完成,给予额外加成  
+                    if (serverProgress >= 1.0 && resourcesCompleted >= estimatedTotal * 0.8) {  
+                      totalProgress = Math.max(totalProgress, 95);  
+                    }  
                       
                       
                     // 更新进度条  
                     // 更新进度条  
                     progressBar.style.width = totalProgress + '%';  
                     progressBar.style.width = totalProgress + '%';  
                       
                       
                     // 更新状态显示  
                     // 更新状态显示  
-                    if (isLoading && totalProgress < 100) {  
-                      statusDisplay.style.display = 'block';  
-                      statusDisplay.textContent =   
-                        \`Loading... \${Math.round(totalProgress)}% (\${resourcesCompleted}/\${estimatedTotal} resources)\`;  
-                    } else if (totalProgress >= 100) {  
-                      isLoading = false;  
-                      statusDisplay.style.display = 'none';  
-                      progressBar.classList.add('complete');  
-                        
-                      // 1秒后隐藏进度条  
-                      setTimeout(() => {  
-                        progressBar.style.display = 'none';  
-                      }, 1000);  
-                    }  
+                    statusDisplay.style.display = 'block';  
+                    statusDisplay.textContent =   
+                      \`Loading... \${Math.round(totalProgress)}% (\${resourcesCompleted}/\${estimatedTotal} resources)\`;  
                       
                       
                     console.log(\`Progress: Server \${Math.round(serverProgress * 100)}%, Resources \${resourcesCompleted}/\${estimatedTotal}, Total \${Math.round(totalProgress)}%\`);  
                     console.log(\`Progress: Server \${Math.round(serverProgress * 100)}%, Resources \${resourcesCompleted}/\${estimatedTotal}, Total \${Math.round(totalProgress)}%\`);  
+                      
+                    // 如果接近完成,开始检测完成状态  
+                    if (totalProgress >= 95) {  
+                      if (completionTimer) clearTimeout(completionTimer);  
+                      completionTimer = setTimeout(checkCompletion, 1000);  
+                    }  
                   }  
                   }  
   
   
                   // 监听服务端编译进度  
                   // 监听服务端编译进度  
@@ -176,10 +214,11 @@ export function progressTrackingPlugin() {
                           if (isRelevantResource && !completedResources.has(entry.name)) {  
                           if (isRelevantResource && !completedResources.has(entry.name)) {  
                             completedResources.add(entry.name);  
                             completedResources.add(entry.name);  
                             resourcesCompleted++;  
                             resourcesCompleted++;  
+                            lastResourceTime = Date.now();  
                               
                               
-                            // 动态调整预估总数  
-                            if (resourcesCompleted > estimatedTotal * 0.8) {  
-                              estimatedTotal = Math.max(estimatedTotal, resourcesCompleted + 5);  
+                            // 更保守的总数调整策略  
+                            if (resourcesCompleted > estimatedTotal * 0.9) {  
+                              estimatedTotal = Math.max(estimatedTotal, resourcesCompleted + 3); // 只加3个缓冲  
                             }  
                             }  
                               
                               
                             console.log(\`Resource completed: \${entry.name} (type: \${entry.initiatorType})\`);  
                             console.log(\`Resource completed: \${entry.name} (type: \${entry.initiatorType})\`);  
@@ -192,26 +231,10 @@ export function progressTrackingPlugin() {
                     observer.observe({ entryTypes: ['resource'] });  
                     observer.observe({ entryTypes: ['resource'] });  
                   }  
                   }  
   
   
-                  // 监控动态导入  
-                  const originalImport = window.import;  
-                  if (originalImport) {  
-                    window.import = async function(specifier) {  
-                      console.log(\`Dynamic import started: \${specifier}\`);  
-                        
-                      try {  
-                        const result = await originalImport.call(this, specifier);  
-                        console.log(\`Dynamic import completed: \${specifier}\`);  
-                        return result;  
-                      } catch (error) {  
-                        console.log(\`Dynamic import failed: \${specifier}\`);  
-                        throw error;  
-                      }  
-                    };  
-                  }  
-  
                   // 初始化  
                   // 初始化  
                   function initialize() {  
                   function initialize() {  
                     estimatedTotal = estimateResourceCount();  
                     estimatedTotal = estimateResourceCount();  
+                    lastResourceTime = Date.now();  
                     console.log(\`Estimated total resources: \${estimatedTotal}\`);  
                     console.log(\`Estimated total resources: \${estimatedTotal}\`);  
                       
                       
                     // 显示初始状态  
                     // 显示初始状态  
@@ -225,14 +248,16 @@ export function progressTrackingPlugin() {
   
   
                   // 页面加载完成后的处理  
                   // 页面加载完成后的处理  
                   function handlePageLoad() {  
                   function handlePageLoad() {  
-                    // 给一些时间让所有资源完成加载  
                     setTimeout(() => {  
                     setTimeout(() => {  
-                      if (resourcesCompleted < estimatedTotal * 0.5) {  
-                        // 如果完成的资源太少,调整预估值  
-                        estimatedTotal = Math.max(resourcesCompleted + 2, 5);  
-                        console.log(\`Adjusted estimated total to: \${estimatedTotal}\`);  
+                      // 最终调整预估值  
+                      if (resourcesCompleted > 0) {  
+                        estimatedTotal = Math.max(resourcesCompleted + 2, estimatedTotal);  
+                        console.log(\`Final estimated total: \${estimatedTotal}\`);  
                       }  
                       }  
                       updateProgress();  
                       updateProgress();  
+                        
+                      // 开始完成检测  
+                      setTimeout(checkCompletion, 2000);  
                     }, 1000);  
                     }, 1000);  
                   }  
                   }  
   
   
@@ -249,11 +274,6 @@ export function progressTrackingPlugin() {
                     }  
                     }  
                   }  
                   }  
   
   
-                  // 错误处理  
-                  window.addEventListener('error', (event) => {  
-                    console.log(\`Resource load error: \${event.filename || 'unknown'}\`);  
-                  });  
-  
                   // HMR 更新时重置状态  
                   // HMR 更新时重置状态  
                   import.meta.hot.on('vite:beforeUpdate', () => {  
                   import.meta.hot.on('vite:beforeUpdate', () => {  
                     console.log('HMR update detected, maintaining progress tracking...');  
                     console.log('HMR update detected, maintaining progress tracking...');