3

Often, when creating single page apps, you need to populate the app with some form of data (i.e. in the json-format). This is usually done through an AJAX-call.

Now, this isn't the best possible solution. The DOM needs to be loaded before the AJAX call is launched, and it's semantically awkward to do this async through javascript.

Is it possible to load a JSON-resource in the same fashion as a <script src="some-file.js"> automatically fetches some-file.js, or fetches some-image.png automatically when the DOM loads?

4
  • Now, this isn't the best possible solution. I would argue that it is. The DOM needs to be loaded before the AJAX call is launched, and it's semantically awkward to do this async through javascript. I don't see how it's awkward. In jQuery, it can be as simple as 1 line of code. Commented Oct 31, 2013 at 13:10
  • Not quite sure what you mean, but some-file.js: data = { "data"} ;? Commented Oct 31, 2013 at 13:12
  • @RoryMcCrossan, I am speaking on a more general level. Why is bootstrap data not considered a resource in the way an image or css file is considered a resource? why should it have to wait to be loaded until everything else is in place? Commented Oct 31, 2013 at 13:17
  • @user234461 - typically, the bootstrapped data comes from a web service or API-like interface. Commented Oct 31, 2013 at 13:18

1 Answer 1

3

The correct MIME type for JSON is application/json

It is possible to include it in the JSON file, as a script. If the path is relative, just use this code

<script type="application/json" src="path/to/json/file.json"></script>

I would disagree, however, that this is semantically awkward. Simply load it with $.getJSON

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer :-) What I mean by semantically awkward is that this data is a resource in the same way an image is a resource or a javascript file is a resource. Why should not data be loaded as a resource as well?
For one, it will delay the loading of the page. This will load synchronously. If you load it using AJAX, it will load the JSON resource after the DOM has finished loading.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.