My root relative links work when I’m developing locally, but not on my GitHub Pages project site.
This is my directory structure
| - data
| | - data.json
| - js
| | - script.js
| - index.html
When I’m developing locally, I can successfully get data from data.json by using the fetch API.
However, my fetch request fails when I deploy my site on GitHub Pages.
This is because it is assumed by the browser that my site lives at username.github.io, when it is in fact in username.github.io/REPO.
So when I do
fetch('/data/data.json'), the browser interprets that as a GET request to
username.github.io/data/data.json, instead of
I could change my URL so that it would include my repo like so:
But then fetch wouldn’t work when I develop locally.
And apparently you can’t use file relative paths as the URL in the fetch method.
So how do I access my data both locally and on GitHub Pages without using absolute URLs?
I have googled and come to a lot of dead ends. The only idea I have is to create a script that would create a build folder and replace script.js with a new script.js file that will have switched
/ links to
EDIT: The problem was that I was using relative links incorrectly. The URL inside the fetch method should have been relative to index.html, not to script.js. So the solution is