Alex Craft
Alex Craft

Reputation: 15336

Dynamic fetch for static HTML page without webserver

There's a static page myapp/page.html and a static file in same directory myapp/data.txt. I would like to open that page in Browser from the file system, without web server, and get content of the myapp/data.txt file. It should be possible periodically reload that file to check if its content changed.

As a last resort it's possible to change data.txt into data.js and load it via script.src='data.js' but maybe it's somehow possible to load it as a text too?

Upvotes: 4

Views: 2713

Answers (1)

Brad
Brad

Reputation: 163262

As a last resort it's possible to change data.txt into data.js and load it via script.src='data.js' but maybe it's somehow possible to load it as a text too?

Yeah, you could use the old JSON-P method, but with a statically-named function.

Basically, you have in your main script something like this:

window.onDataLoad = (data) => {
  // do something with data here
}

// Inject script tag wherever you want to reload the data
const scriptEl = document.createElement('script');
scriptEl.src = 'data.js';
document.querySelector('head').appendChild(scriptEl);

Then, in your data.js, something like:

window.onDataLoad( << YOUR DATA HERE >> );

Finally... just wanted to note that I sympathize! It's ridiculous that fetch() can't handle this. What a great opportunity to abstract the fetching of data from HTTP, when moving away from XHR. Sadly, this didn't happen.

Upvotes: 2

Related Questions