How to use JavaScript to see if a URL's resource exists?

16 hours ago 3
ARTICLE AD BOX

I'm using JavaScript to load the navbar, sidebars, and footers for my website. I have a "default" asset for my website, and I have the JavaScript working to load that if it doesn't find another applicable HTML file in the same directory. Here is the snippet of the code that I'm working on:

// 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"); }

I'm not sure how to test if the URL resource exists before I try to load it. My plan is to see if there is an applicable HTML file, and if so, load that resource. Otherwise, I plan to use the default element as defined up top with newElement.

To be clear, I'm not looking to see if pathURL is a potentially valid URL; I want to see if there is a file that currently exists using pathURL's path.

I am brand-new to JavaScript, so I'm unsure of all of the tools that are available to use. Any help would be appreciated, as I am brand new to JavaScript, and I'm not sure of best practices.

Read Entire Article