Upload JSON file using script tag

I wrote a small I18n plugin that accepts different languages ​​through json. To make use as simple as possible for the user, I want them to be able to simply flip their json package directly on the page along with the actual script:

<script id="pop-language_es" type="application/json" src='languages/es.json'></script>
<script src='pop.js'></script>

To support this plugin as accurately as possible, I want to avoid external dependencies such as jQuery. I can get the script tag using pure js:

var json = document.getElementById("pop-language_es");

The problem is that this is only a tag, not the actual json. Is there a way to get content with something like json.content?

There is a similar question here in which several people recommend using Ajax. This will definitely work in this situation, but will it not cause the client to download json twice? (First, while loading the page, then again during the Ajax call.) If so, I hope that there will be a better option, since these json files can become quite large.

+3
source share
2 answers

What you can do is set a global variable in your external file:

window.myJSON = { ... };

Then your other code can access this data through window.myJSON.

I'm not sure how the browser parses files .json, so you might need to change the extension to .js.

+4
source

javascript (, ...) . document.getElementById , DOM, .

0

All Articles