What's the best approach to load initial data

2019-04-22 18:34发布

In Backbone.js, model loading and saving is done via ajax calls. However, are there any best practices to loading the initial collection on page load without having to pull this down via ajax? I'm trying to do as much server side rendering as possible up front.

In the past, I've seeded the html with a javascript variable containing a json string of the initial data state so it can be rendered server side, but I'm not sure if this is a good practice.

3条回答
Melony?
2楼-- · 2019-04-22 19:27

From Backbone docs, initialising models in script tag is not a bad practice. In my current project I decided to set only plain objects inside window.projectData, to be able to init Backbone models in external javascripts.

<script>
  ;(window.projectData || (window.projectData = {})).modelName = {/* value */};
</script>
查看更多
\"骚年 ilove
3楼-- · 2019-04-22 19:27

The approach you select will probably depend on how much data you're planning to load and how that data will be used within the page.

If most of the required data will not ultimately end up rendered on the page, bootstrapping the initial state into a javascript variable might not be a bad route.

If the data is directly related to the presentation of the page, however, you might prefer to parse a pre-rendered DOM for the initial state of the backbone application. The obligatory word of caution is that this kind of parsing will be somewhat slower, especially for large data sets.

If you do end up opting to parse pre-rendered content, I put together a small jQuery DOM parser a while back that might prove useful for mapping the presented content into a Backbone-ready form.

查看更多
可以哭但决不认输i
4楼-- · 2019-04-22 19:33

Don't know if it's necessarily the best practice, but this method of seeding the html with a json object (not a json string as you described it, right?) is certainly my preferred way of doing initial loading. Not only for the (obvious) reason that it removes the delay of waiting for the initial AJAX call to return, but also because the one less open connection frees the browser to load something else instead (like an img src or whatnot), getting you to document.onLoad slightly sooner.

It's recommended that, when using this method, you put the said variable in a script tag at the bottom of the body (i.e. not in the head section), in order to give the static html elements on the page a chance to load and render first. The json data is ready when document.onLoad fires.

查看更多
登录 后发表回答