Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best approach to load initial data in Backbone.js?

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.

like image 862
James Avatar asked Oct 25 '12 18:10

James


People also ask

What is the only method available in the backbone JS history?

There is only method named "start" can be used to manipulate the Backbone. js history.

How Backbone js works?

BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications. When a model changes, it automatically updates the HTML of your application. BackboneJS is a simple library that helps in separating business and user interface logic.

What is Backbone used for?

Backbone helps developers manage a data model in their client-side web app with as much discipline and structure as you would get in traditional server-side application logic.


2 Answers

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.

like image 80
meetamit Avatar answered Sep 24 '22 17:09

meetamit


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>
like image 35
Andrey Kuzmin Avatar answered Sep 22 '22 17:09

Andrey Kuzmin