How to access JSON data loaded in a script tag with src set with JavaScript?

Spread the love

Sometimes, we want to access JSON data loaded in a script tag with src set with JavaScript.

In this article, we’ll look at how to access JSON data loaded in a script tag with src set with JavaScript.

How to access JSON data loaded in a script tag with src set with JavaScript?

To access JSON data loaded in a script tag with src set with JavaScript, we assign the object to a variable.

For instance, we write

mainJson = { foo: "bar" };

in json-content.js.

Then we write

<script src="json-content.js"></script>
<script>
  console.log(mainJson);
</script>

to add the script tag to load json-content.js.

And then we log the mainJson value in the 2nd script tag.

Conclusion

To access JSON data loaded in a script tag with src set with JavaScript, we assign the object to a variable.

Leave a Reply

Your email address will not be published. Required fields are marked *