Async fetch and then access to the result from enqueued JS

Viewed 32

This question is not a case when something doesn't work or working wrong - I just need to be sure the following solution would be always working.

In main.js I fetch a JSON string from a JSON file and after that I enqueue another JS file which needs to work with the fetch result:

async function read() {   
    const response = await fetch('http://localhost/data.json');
    return response.text();
}

let jsonObj;
read().then((jsonStr) => {
    jsonObj = JSON.parse(jsonStr);
    enqueueJS();
});

function enqueueJS() {
    let script = document.createElement('script');
    script.src = '/data_process.js';
    document.body.appendChild(script);
}

I just need to be sure: will the data_process.js file have always access to the jsonObj global variable or see it regardless of the duration of the fetch request in the main.js?

1 Answers

Since you don't call enqueueJS until the value is assigned to jsonObj, the data will exist there before the script is created.

It's conceivable that some other code might overwrite it before the generated script element is executed though.

And passing data about using globals is inelegant at best.


Better approaches to the problem include:

  • data_process.js providing a function that you call and pass the data to (with data_process.js being loaded normally, and first)
  • data_process.js being responsible for fetching the data itself

You might also consider assigning the data to the script element and reading it from there. That does at least link the data to the script that is using it instead of having it exist as a global.

script.dataset.data = jsonStr;

with

 const data = JSON.parse(document.currentScript.dataset.data)

inside data_process.js.

Related