Issue
I'm working on a web page using VS Code.
I noticed that when I serve and open it using the Live Server extension, my background image loads correctly.
But when I open the index.html file through my operating system / desktop environment's native file explorer application, which opens the file in my default browser with the file://
protocol, the background image doesn't load correctly and the developer tools shows:
Failed to load resource: net::ERR_FILE_NOT_FOUND.
Why does this happen?
I tried to open my index.html file with other browsers, but that also didn't work.
Here is the code where my CSS file is specifying an image file as a background image:
body {
background-image: url("/images/background_home.jpg");
background-size: cover;
background-repeat: no-repeat;
font-family: "Roboto", sans-serif;
position: relative;
}
Solution
It has to do with the way you wrote the path: You wrote an absolute path (one that starts with a "/"). Absolute paths get resolved by Live Server relative to the root of the live server (see the liveServer.settings.root
setting, which by default, is the workspace folder open in VS Code), and relative to the filesystem drive root by the browser when viewing pages using the file://
protocol.
You can solve the problem by using relative paths (if you're okay with that). But once you're at the point where you're using a local file server like Live Server, it usually means that you actually need it for other purposes (Ex. to load certain kinds of files that browsers will intentionally not load through their support for the file://
protocol for security reasons, such as (if I recall correctly) JSON files, certain web graphics files like shaders, etc.)- at which point, I don't think there's much point trying to support both, and that you should just do what you think is best only supporting a local server like Live Server.
If you eventually want to serve your site through a different kind of server, then considerations for how you write the path may change again, or you may have to configure the way that server resolves paths in the web requests it receives and responds to, but that's a different story.
Answered By - starball
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.