load known data

This page contains examples of loading data from a known location using fetch() or ESM, which allows for separation of code and data, and works on static sites.

fetch()

Using the fetch api, it's possible to load json files at known locations for use as normal objects.

If opening your pages locally as files with the file:// procotol, this may be stopped by CORS. You can get around this by changing browser settings, but I don't recommend it. If serving your files from the same domain, or using localhost with a local http server, this will work fine!

The example.json file's contents, fetched and inserted into the page:

Another caveat is that the fetch api returns a promise, one of javascript's mechanics for asynchronous code. Here is the source code, with varying ways of interacting with promises:

ESM

Using ecmascript modules, it's possible to export and import things consistently between scripts. This lets you store your data in a separate javascript file, as well as whatever else you want in javascript, such as functions.

Like with the fetch api, this won't work in some browsers when using the file:// procotol, as it will be blocked by CORS. And similarly to the fetch api, it will work when using a local http server to serve your files and accessing your site using localhost.

Something to note is that ecmascript modules must be used with type attribute on your script tags:

<script type="module" src="esm.js"></script>

The example.js file's export, imported and inserted into the page:

Source code here.

Using a server for local testing

There are many options in this regard, from the long lived nginx and apache, to newer options such as caddy.

However, they aren't particularly beginner friendly, nor convenient to setup and use on windows.

I would personally recommend using the following python command, which serves the current working directory on the port given:

python3 -m http.server 3000

That uses port 3000, so it would make your site accessible to you at localhost:3000 in your browser.

It is explained further by the articles here or here if you want to learn more, and Python can be downloaded here.

There is also the Live Server visual studio code extension, which is probably the easiest and most simple method.