Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I fetch relative to a JavaScript file

I have a file tree:

index.html

  | js
  |
  | data.json
  | script.js

index.html is just script.js

script.js:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(async function() {
  var req = await fetch("data.json");
  var json = await req.json();
  ...
})();

I’m trying to access data.json from script.js (js folder) instead of index.html.

So I can’t just use js/script.js

How would I do this?

>Solution :

Apparently you can get a path to the currently running script (if it’s not ESM), using document.currentScript

Untested, but this would suggest you can build the path like this:

const dataUrl = new URL('data.json', document.currentScript.src);
const req = await fetch(dataUrl);
// etc
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading