如何用JavaScript判断一个URL的资源是否存在?
我在用JavaScript来加载我的网站的导航栏、侧边栏和页脚。我为网站准备了一个“默认”的资源,并且已经实现了在同一目录下找不到其他合适的HTML文件时加载它的JavaScript。下面是我正在处理的代码片段:
// Loads the element as the default Main asset if a new one is not present
function loadElement(elementID){
// Define the path variable as a placeholder
let newElement = "/assets/main/" + elementID + ".html";
// Define the currently loaded document's path
const docURL = document.URL;
// Find the last "/" in the URL
const lastSlash = docURL.lastIndexOf("/") + 1;
// Trim the docURL into the pathURL
const docDir = docURL.substring(0,lastSlash);
// Find the possible element to load
const pathURL = docDir + elementID + ".html";
// TODO: Test if the new URL exists here
// Fetch the Element data to be loaded
fetch(newElement)
.then(data => {
return data.text() // Return the text from the asset
})
.then(data => {
document.getElementById(elementID).innerHTML = data; // Set the text of the Element to the text from the asset
})
}
// When the window loads, load the Elements specified below
window.onload = () => {
loadElement("navbar");
loadElement("left-sidebar");
loadElement("right-sidebar");
loadElement("footer");
}
我不确定在尝试加载之前,应该如何测试该URL资源是否存在。我的计划是先判断是否存在一个可用的HTML文件,如果存在就加载该资源。否则,我计划使用上方通过 newElement 定义的默认元素。
为避免歧义,我不是在看 pathURL 是否是一个可能有效的URL;我是要查看是否存在使用 pathURL 路径的实际文件。
我对JavaScript完全是新手,所以不太清楚有哪些工具可用。任何帮助都会很感激,因为我是JavaScript的初学者,也不确定最佳实践。
解决方案
方案1:
你可以像下面这样添加一个检查,因为它不需要下载完整的文件数据,所以会更快。
async function checkUrlExists(url) {
try {
const response = await fetch(url, { method: 'HEAD' }); // HEAD avoids downloading the full file
return response.ok; // Returns true for 200-299 status codes
} catch (error) {
return false; // Network error or URL does not exist
}
}
// Usage
checkUrlExists('https://example.com').then(exists => {
console.log(exists ? "Exists!" : "Does not exist.");
});
或者
方案2:
你可以在收到响应后直接进行检查。
function loadElement(elementID) {
// 1. Define your paths
const defaultAsset = "/assets/main/" + elementID + ".html";
const docURL = document.URL;
const lastSlash = docURL.lastIndexOf("/") + 1;
const docDir = docURL.substring(0, lastSlash);
const pathURL = docDir + elementID + ".html";
// 2. Attempt to fetch the local file first
fetch(pathURL)
.then(response => {
// Check if the file exists (status 200-299)
if (response.ok) {
return response.text();
}
// If not found, fetch the default asset instead
console.log(`${elementID} not found at ${pathURL}, loading default.`);
return fetch(defaultAsset).then(defaultRes => defaultRes.text());
})
.then(htmlContent => {
document.getElementById(elementID).innerHTML = htmlContent;
})
.catch(error => {
console.error(`Error loading ${elementID}:`, error);
});
}
使用哪种方案完全取决于你。如果你的HTML文件很小,我建议你选择第二种方案。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。