In this post i want to discuss a simple optimization technique for faster loading web applications.
Suppose your web application needs to show a list of items from the database, you use ajax, so when the page loading is complete your javascript code will create an http request to the server to get the data in JSON format.
This is a common pattern, however you can improve the user experience by delivering faster page loading times, how?.
Loading the initial data when the page is rendered and embedding it with the page.
Using this technique you render the proper javascript code with the object initialization to your data.
This simple technique is useful because if the dataset is small (for example a list of countries) then it can be embedded in the html page request. You could also load the initial paged results of a large dataset in this way. True, you have to add a little more code compared to the classic “always make an additional request after the page is done”, but your users will be happier.
If you are using ASP.NET MVC You can use the HTML helper included in the sample code. It takes a list of the objects you want to embed in the html page. (The .NET JSON serializer will be used to create an array), you also pass the name of the javascript namespace and variable where the object will be assigned.
The result is a <script> tag with the correct javasript variable assignation, so your javascript code will have access to the json data.
It looks like this:
<%=Html.RenderJavascriptVariable("Application.Global","clientList",Model) %>
The first parameter “Application.Global” is the namespace in javascript where the variable will be created. In the example, the variable is called clientList and will be accessible using Application.Global.clientList. In the example, the data serialized will be in the model, however you can also use ViewData.
Download sample code(ASP.NET MVC Solution)
FrontEnd engineering , Web development, innovation, Web Standards, Entrepreneurship.
Leave a reply