0

I have my index.html & data.json file both in the same directory
so how do I access the json file from index.html?

maybe something like this in the index.html :

<script>
  const data= require('./data.json') //obviously this won't work
</script>

according to all the answers for this question, you have to first send the index.html file then make a fetch request back to the server to send you the json file

but is there no way to send both of them together to avoid delay?

2 Answers2

0

You can embed the JSON in the HTML document, either by hard-coding it or using server-side programming to generate the HTML.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I'm really trying to avoid hard coding json it kinda defeats the purpose of having a json file –  Dec 04 '21 at 19:29
  • Then you can embed it in the HTML file with server-side programming as I said. – Quentin Dec 04 '21 at 19:30
  • you mean make the server hard code json into the html file I'm sending? still seems like there might be a better way –  Dec 04 '21 at 19:31
  • 3
    @cakelover Either the JSON is embedded in the HTML file or there are two HTTP requests. – Quentin Dec 04 '21 at 19:44
  • very well, I was hoping maybe there is some way both could be sent at the same time that I missed but I guess there is no such way, thank you for the explanation :) –  Dec 04 '21 at 21:15
0

You can fetch the file for where it's being server.

<script>
  (async () => {
    raw = await fetch('/data.json')
    data = await raw.json()
  })().catch(console.warn)
</script>
The Fool
  • 16,715
  • 5
  • 52
  • 86
  • I'm specifically trying to avoid this because it has a delay of waiting for the fetch –  Dec 04 '21 at 19:32
  • One way or the other the file must be requested from where its being served. There is no way around that. – The Fool Dec 04 '21 at 19:33
  • @cakelover, either you keep the file content together in the first place, you put the files together with server side rendering, or you request the files separately. HTTP/2 and http/3 preload / "server push" begins to address this but still in draft: https://www.smashingmagazine.com/2017/04/guide-http2-server-push/ – erik258 Dec 04 '21 at 19:44
  • 1
    From the question : "you have to first send the index.html file then make a fetch request back to the server to send you the json file but is there no way to send both of them together to avoid delay?" - this is explicitly what the OP is trying to avoid. – Quentin Dec 04 '21 at 19:45
  • 1
    @Quentin, I must admit I havent read the question properly. But, this is explicitly how html works. The file is only parsed and interpreted by the users' browser, so it's the only place from where something like an import can be made. The way the web works, this means making a request. You can hardly request it from the user's hard drive. Alternatively, someone has suggested embedding the file content, which OP also doesn't want. OP wants the impossible. – The Fool Dec 04 '21 at 19:51