简体   繁体   中英

Loading a JSON file via a script tag

I've written a small I18n plugin that accepts different languages via json. To make usage as simple as possible for the user, I want them to be able to just plop their json package directly in a page's along with the actual script:

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

To keep this plugin as lean as possible, I want to avoid external dependencies like Jquery. I can retrieve the script tag using pure js:

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

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

There's a similar question here , in which several people recommend using Ajax. That would definitely work in this situation, but wouldn't that result in the client downloading the json twice? (First during the page load, then again during the Ajax call.) If so, I'd hope there's a better option, as these json files can get quite large.

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

window.myJSON = { ... };

Then your other code can access that data via window.myJSON .

I'm not sure how browsers parse .json files so you may need to change the extension to .js .

Once you include your javascript file, you are able to access it's content (variable,methods,...) within your main file. document.getElementById has nothing to do with the contents on it, it is only looking for the DOM element itself, not the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM