My file structure looks like this
app/
index.html
script.js
data.json
Does that make sense? Now, I want to randomly select an object from my JSON data and display it to the user each time the document loads. However, I'm facing an issue with efficiently accessing the data from my data.json
. Using XMLHttpRequest() or the fetch API seems like overkill for such a simple task. I mean, you don't need to send an HTTP request to link your CSS and HTML files, right?
I've tried linking my data using
<script id="data" src="./data.json" type="application/json"></script>
but it didn't work as expected. A workaround I found was renaming data.json
to data.js
, adding a var data =
prefix to the JSON data, and importing it into index.html
. This method feels hacky and not optimal.
It seems like there may be some issues related to CORS/Same-origin that I don't fully understand. Can someone provide a detailed explanation on why an HTTP request is necessary to access a local file? Why can't we simply link our JSON data like we do with HTML, CSS, and JS files using link/script tags?