You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript检测URL对应的资源是否存在?——网站公共组件按需加载技术问询

How to Check for Local HTML Resources Before Loading Fallback Content

Hey there! I get that figuring out how to verify if a local HTML file exists before loading it can be tricky when you're new to JavaScript—let's break this down and fix your code.

The Core Issue & Workaround

Here's the thing: frontend JavaScript can't directly peek at the server's file system to check if a file exists (thanks to security rules like the same-origin policy). So instead of checking first, we have to try loading the local file first, and if that fails (like we get a 404 error), we fall back to your default resource.

Modified Code Implementation

Here's how to update your loadElement function to handle this logic properly:

function loadElement(elementID) {
    // Define your paths like before
    const defaultPath = "/assets/main/" + elementID + ".html";
    const docURL = document.URL;
    const lastSlash = docURL.lastIndexOf("/") + 1;
    const docDir = docURL.substring(0, lastSlash);
    const localPath = docDir + elementID + ".html";

    // First attempt to load the local resource
    fetch(localPath)
        .then(response => {
            // Check if the fetch was successful (status 200-299)
            if (response.ok) {
                return response.text();
            }
            // If local resource fails, throw an error to trigger the fallback
            throw new Error("Local resource not available");
        })
        .then(content => {
            // Inject the local content into the element
            document.getElementById(elementID).innerHTML = content;
        })
        .catch(() => {
            // Fallback to the default resource if local load fails
            fetch(defaultPath)
                .then(response => response.text())
                .catch(error => {
                    // Handle rare case where even default fails (optional)
                    console.error(`Failed to load default ${elementID}:`, error);
                    return ""; // Return empty to avoid breaking the chain
                })
                .then(content => {
                    document.getElementById(elementID).innerHTML = content;
                });
        });
}

// Load elements once the page is ready
window.onload = () => {
    loadElement("navbar");
    loadElement("left-sidebar");
    loadElement("right-sidebar");
    loadElement("footer");
};

Key Details to Keep in Mind

  • Response Validation: We use response.ok to check if the fetch succeeded—this covers all 2xx status codes (not just 200), making the check more robust than looking for a specific status code.
  • Error Handling: The catch block triggers if the local fetch fails for any reason (404, network error, etc.), and immediately falls back to your default resource.
  • Server Setup: Make sure your server returns a proper 404 status code when the local HTML file doesn't exist. Some servers send a 200 status with a custom "not found" page, which would trick our code into thinking the file exists.
  • Same-Origin Policy: This works because localPath is in the same origin as your page. If you ever need to fetch resources from another domain, you'd need to configure CORS on that server.

Optional Nice-to-Haves

  • Loading States: Add a loading spinner or placeholder text (like "Loading...") to the element before fetching, then replace it once content loads.
  • Caching: If these elements don't change often, cache the fetched content with localStorage to reduce repeated network requests.

内容的提问来源于stack exchange,提问作者spriterjohnson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 06:37:56