"A key aspect of Web application performance is site response time. See how you can boost it by preloading page data and displaying content only when appropriate"
Developing a Web application involves many design considerations and decisions. The most important is often response time—a performance consideration. One approach to improving site response time is to preload content and then display it only when the user needs to see it. You can do this by taking advantage of Dynamic HTML (DHTML) and JavaScript.
Each element within an HTML page is accessible via JavaScript. The DHTML style property contains the visibility property, which lets you control whether the element's contents are displayed on the page. To do this, you set the property to either visible or hidden. The following syntax may be used to access the property via JavaScript:
document.element_name.style.visibility = "visible";
or
document.element_name.style.visibility = "hidden";
The actual element is easily located by using its ID attribute and the getElementById JavaScript method:
document.getElementById("element name").style.visibility = "hidden";
Remember, HTML elements are assigned ID attributes to distinguish them within the page. This allows DHTML and JavaScript to locate and work with individual elements. The following HTML sample assigns individual names to HTML header elements and uses JavaScript to show and hide the second header:<html>
<head>
<title>div test</title>
</head>
<body>
<h1
id="header1"
onMouseOver='document.getElementById("header2").style.visibility="hidden";'
onMouseOut='document.getElementById("header2").style.visibility = "visible";'>
Now you see it!
</h1>
<h2 id="header2">
Now you don't!
</h2>
</body>
</html>
The code uses the onMouseOver and onMouseOut events of the first header element to show and hide the second header element. Notice that the name assigned to the second header via the ID attribute is used to control its visibility in the JavaScript.
This approach to displaying and hiding content is beneficial when only portions of a document are displayed at a time. It may be applicable for menus, expanding/collapsing page regions, and so forth. You can use this technique with any HTML element, but the DIV element stands out as a prime candidate when working with chunks of a page.
What is DIV?
The DIV element is used to give structure and context to block-level content within an HTML document. Everything between the start and ending DIV tags constitute the block, and the characteristics of the contained elements are controlled either by the DIV tag attributes or by applying style sheet formatting to the block. The DIV tag is supported by both Internet Explorer and Netscape browsers.
DIV vs. SPAN
Many developers confuse the DIV element with the SPAN element. Although they have the same characteristics, SPAN is used to define inline content as opposed to block-level content. You would use a DIV tag for a paragraph, but a SPAN tag would be useful for applying special characteristics to one or more words within the paragraph.
The DIV tag allows you to divide a Web page to handle formatting and presentation. You can combine it with the visibility technique to divide page content and show it as you choose. The following code sample uses the DIV tag to divide the page into sections; hyperlinks show and hide the sections:<html><head>
<title>div test</title>
<script language="JavaScript">
function setAllVisible() {
document.getElementById("section1").style.visibility="hidden";
document.getElementById("section2").style.visibility="hidden";
document.getElementById("section3").style.visibility="hidden";
document.getElementById("section4").style.visibility="hidden";
}
</script></head>
<body onLoad='setAllVisible();'>
<h1>Builder.com Sample</h1>
<ul>
<li><a href="#"
onClick='
document.getElementById("section1").style.visibility="visible";
document.getElementById("section2").style.visibility="hidden";
document.getElementById("section3").style.visibility="hidden";
document.getElementById("section4").style.visibility="hidden";'>Section 1</a></li>
<li><a href="#"
onClick='
document.getElementById("section1").style.visibility="hidden";
document.getElementById("section2").style.visibility="visible";
document.getElementById("section3").style.visibility="hidden";
document.getElementById("section4").style.visibility="hidden";'>Section 2</a></li>
<li><a href="#"
onClick='
document.getElementById("section1").style.visibility="hidden";
document.getElementById("section2").style.visibility="hidden";
document.getElementById("section3").style.visibility="visible";
document.getElementById("section4").style.visibility="hidden";'>Section 3</a></li>
<li><a href="#"
onClick='
document.getElementById("section1").style.visibility="hidden";
document.getElementById("section2").style.visibility="hidden";
document.getElementById("section3").style.visibility="hidden";
document.getElementById("section4").style.visibility="visible";'>Section 4</a></li>
</ul><br>
<div id="section1">Section 1 text.</div>
<div id="section2">Section 2 text.</div>
<div id="section3">Section 3 text.</div>
<div id="section4">Section 4 text.</body>
</html>
The code includes a JavaScript function to hide all DIV elements. The function is called when the document is loaded. Clicking each hyperlink shows the related section and hides the others. The drawback is that these methods are supported only in Internet Explorer 5 and above and Netscape Navigator 6 and above. However, I tested it with Mozilla 1.01 with no problems.
Display information only when necessary
Combining the power of DHTML and JavaScript enables you to preload page content and display portions when appropriate. This increases response time, thus improving performance for the user.
Tuesday, July 15, 2008
Increase site performance by selectively displaying preloaded content
Friday, July 11, 2008
Improving ASP.NET Application Performance and Scalability
any factors influence application performance, but in essence, the most important is to be aware of how to optimize your applications so they consume the least amount of memory and require the least amount of processing to produce the desired output in a managed environment.
This article discusses some best practices that you can follow during an application's development life cycle to help ensure that your application is both scalable and achieves high performance. You don't have to use special tools to achieve this, just write structured, readable code, paying particular attention to techniques that are instrumental for improving, optimizing and boosting the performance of .NET applications.
Reducing Page Load Time
Avoid excessively large images, redundant tags, and nested tables to facilitate faster page loads. Always avoid unnecessary roundtrips to the web server. Use client side scripts to dramatically reduce server roundtrips, thereby boosting the perceived, if not the actual application performance. Take advantage of the Page.IsPostback property to avoid unnecessary server processing on a roundtrip, reducing network traffic. I suggest you leave page buffering on (it is turned on by default) for a page unless you have a specific reason to turn it off.
You can pre-compile web pages in your application to reduce the working set size and boost application performance. Set AutoEventWireup attribute to false in the
<configuration>
<system.web>
<pages autoeventwireup="true|false">
</system.web>
</configuration>
The AutoEventWireup attribute accepts a Boolean value that indicates whether the ASP.NET pages events are auto-wired. If the AutoEventWireup is set to false, the runtime does not have to look for each of the page event handlers. This MSDN article about the AutoEventWireup Event concludes with, "When you explicitly set AutoEventWireup to true, Visual Studio .NET or Visual Studio 2005, by default, generates code to bind events to their event-handler methods. At the same time, the ASP.NET page framework automatically calls the event-handler methods based on their predefined names. This can lead to the same event-handler method being called two times when the page runs." The article therefore recommends that you always set AutoEventWireup to false while working in Visual Studio .NET.
Efficient ASP.NET State Management Practices
ViewState is great for storing control state but can degrade performance—especially on web sites with large page sizes. If you've ever looked at a page that contains a large DataSet, you know the amount of data stored in ViewState can be overwhelming. Every byte added to a web page by enabling its ViewState causes two bytes of network traffic, one in each direction. Evaluate whether each web page you write requires ViewState and avoid it when possible to speed up the page-load cycle in your applications. You should typically use ViewState only for controls that need to persist state. You can turn ViewState on or off at four levels: machine, application, page, and control. Limiting the size of the ViewState and eliminating its unnecessary usage would boost the application performance to a large extent due to the reduced size of the rendered pages and hence the network traffic. It should be noted that each byte of the view state causes two bytes of network traffic for each request, one from the server to the client and the other from the client to the server. For more information on ViewState and how to turn it off at control, page, application, or machine levels, see this article .
You can remove the runat="server" form tag completely to reduce page size by 20 bytes. If you don't remove this tag, the page itself passes on about 20 bytes of information to ViewState—even when the page's ViewState property is set to false.
Caching is one of the best strategies for storing relatively static application data. Caching reads data from memory to avoid repeatedly retrieving data from a database, file, or any other repository, and it can provide huge application performance gains. Use Page Output, Page Fragment or Data Caching directives depending on your requirements. Cache application-wide data that multiple users of the application need to share and access, but avoid storing user-specific data in the cache.
Use Session State only for storing a single user's session data. Avoid storing too many objects in the Session and turn Session State off for pages that do not need to access session data. You can turn Session State on or off at the same four levels as ViewState: machine, application, page, and control.
Note that there are three Session State storage modes. The right type of storage mode to choose depends on factors such as, speed, security, scalability, and reliability. Even though the InProc mode of Session State storage is the fastest, it is not at all well suited to a production environment and not scalable for large sites. The OutProc storage mode is well-suited for web sites with heavy traffic, while the SqlServer mode is great for securing session data. No matter which mode you choose though, Session State has one major disadvantage: the resource will be increasingly strained as you scale up. There are always tradeoffs. The best mode for security, scalability, and reliability is not always the best mode for performance, and vice versa.
Tips for Efficient Memory and Resource Management
I've listed a few tips in this section that can help you avoid problems. I don't have room to explain each tip in-depth here; instead, I've provided a basic description and added links where appropriate so you can explore further on your own.
Try never to refer to a short-lived object from a long lived one to avoid promoting short-lived objects to higher generations. Note that the .NET Garbage Collector (GC) works more frequently against lower generations than against higher ones. An in-depth discussion of the .NET GC is beyond the scope of this article, but this two-part MSDN article on garbage collection (Part 1, Part 2) provides more background
Avoid any code that can promote an object to a higher generation unnecessarily as shown in the code snippet below:
class Employee
{
EmployeeRegister empRegister;
void Create (int empCode, int deptCode, double basic)
{
EmployeeRegister empRegister = new EmployeeRegister();
empRegister.Create(empCode, deptCode, basic);
this.empRegister = empRegister;
}
}
Use Dispose and Finalize appropriately to handle unmanaged resources (for more information, see my article When and How to Use Dispose and Finalize in C#. In fact, you should avoid implementing the Finalize method as much as possible.Set any objects no longer required to null prior to making any long-running calls. Developers often set locals to null after they're done using them, but in .NET, that's not required, as the GC can safely determine when objects are no longer needed or are not reachable, thus making them eligible for garbage collection. However, if you use machine resources such as files, database connections, or unmanaged objects, remember to release them in a finally block—never in a catch block.
Author's Note: In C#, it's best to wrap resource-handling code within a using block to ensure that the resources are disposed of properly when they're no longer needed. When you use the statement, the .NET framework implicitly creates usingfinally blocks for those objects that implement IDisposable.
Acquire resources and locks late and dispose of them as soon as possible. Ensure that you free or dispose unneeded resources and locks properly. In fact, I recommend that you avoid locking and synchronization altogether unless it's absolutely necessary. Do not lock on the this object—it's better to lock on a private object. If you lock on the current object instance (this), all the members of the object are also locked irrespective of whether a lock is required on them. Do not lock on object types, only on objects themselves
Efficient Exception Management
Exceptions are errors that occur at run time. Exceptions are generally well understood but quite often used improperly. An understanding of proper exception handling is one of the more important aspects of efficient programming.
Handle only those exceptions that you know how to handle and avoid handling those that you don't know how to handle. As Eric Gunnerson, a former member of Microsoft's C# team, says in his blog, "the essence of exception handling is to be able to respond to a specific exception in a specific situation."
When possible, reduce the number of try...catch blocks in your code; exceptions take longer to be processed and can reduce application performance drastically. Do not use exceptions to control an application's logic flow. Use proper validation techniques instead of exceptions to avoid throwing unnecessary exceptions.
Efficient Data Access Strategies
Prefer DataReaders to DataSets. DataReaders are much faster than DataSets for simple sequential data access. Use a DataReader for fast data-rendering, but not to pass data between layers of the applications or through different application domains—unlike DataSets which can work in disconnected mode and can be cached, DataReaders always require an open connection. When you do have to use a DataSet, you can often set its EnableConstraints property to false and use the BeginLoadData and EndLoadData methods for faster data rendering. If you are using transactions keep them short to minimize the lock durations and to improve data concurrency.
Open database connections as late as possible and close them immediately when done. Effective use of connection pooling can increase application performance by reducing the number of roundtrips to the server. Note that each database request in a distributed environment creates network traffic that can cause performance bottlenecks and degrade the application's performance. Try to minimize the number of database connections in the application. Never hold a connection open, because that decreases the number of available connections in the connection pool and hence degrades performance if the demand for connections exceeds the pool count. See this article for more information on connection pooling.
Avoid late binding whenever possible. Late-binding adds flexibility but is always slow compared to early binding. Note that using virtual methods in your code requires late binding, because virtual methods must be mapped. Any class that contains a virtual method has its own virtual table. The virtual table in turn contains entries that correspond to the virtual methods that the class contains. Note that the virtual method is class specific; there can be only one virtual table per class regardless of how many virtual methods the class contains. The runtime uses the virtual table to map a virtual method to the object on which it is called. Hence there's additional overhead involved (more resource usage—both processor and memory) in binding a virtual method to the object on which it is called to satisfy a virtual method call.
You should seal final classes (those that cannot be inherited) for performance gains.
Avoid recursive method calls and try to replace them with loops instead. Inline frequently called code inside loops. Avoid calling methods or properties repetitively inside a loop. Especially, avoid situations that will require boxing and unboxing of value types, because that carries performance overhead—use generics instead when possible, building strongly typed collections to avoid boxing and unboxing issues. This link provides more information.
Avoid inefficient string operations (see this article for more information) and use collections (if needed) efficiently.
Choosing between Server.Transfer and Response.Redirect
Use the Server.Transfer method to redirect between pages in the same application; Server.Transfer avoids an unnecessary client-side redirection. However, you cannot always just replace Response.Redirect calls with Server.Transfer. If you need authentication and authorization checks during redirection, use Response.Redirect instead. The two mechanisms are not equivalent. When you use Response.Redirect, make sure you use the overloaded method that accepts a Boolean second parameter, and pass a value of false to ensure an internal exception is not raised. Also note that you can only use Server.Transfer to transfer control to pages within the same application. To transfer to pages in other applications, you must use Response.Redirect.
Use Best Practices—and Common Sense
Even though there is no specific methodology that can fit in each and every environment, using best practices such as those discussed in this article can yield better application performance. You should plan and set some well-defined performance objectives, create performance test plans, performance checklists, and perform periodic tests based on the test plans. Keep these performance factors in mind when designing applications. This process should be iterative and repeated until we meet the predefined performance goals.
Application Performance Issues Cause Organizations to Lose Millions, According to New Aberdeen Group Study
LEXINGTON, Mass., July 8 /PRNewswire/ -- Application performance issues
are impacting overall corporate revenues by up to 9 percent, according to a
new benchmark report by Aberdeen Group, a Harte-Hanks company (NYSE: HHS)
sponsored in part by Gomez, Inc., a leading provider of web application
experience management services.
Entitled "The Lifecycle Approach Brings IT and Business Together," the
report surveyed 206 organizations between May and June 2008 and found that
58 percent of the organizations surveyed are unsatisfied with the
performance of applications that they currently use. Their top challenge is
the inability to identify issues before end users are impacted.
"Being proactive about managing application performance is no longer
optional," said Bojan Simic, research analyst, Aberdeen. "What can no
longer be ignored is the impact that application performance is having on
some of the key metrics such as revenue growth, customer satisfaction,
employee productivity, and profitability."
Using key performance criteria to distinguish Best-in-Class companies
from Industry Average companies and Laggards, the report found that
Best-in-Class companies were five times more likely to report improvements
in quality of end user experience. It found that 65 percent of
Best-in-Class companies have the ability to measure the quality of end user
experience, with 81 percent reporting improved customer satisfaction.
Additionally, what allowed Best-in-Class organizations to outperform
the overwhelming majority of their peers was a full lifecycle approach to
application performance management including the deployment of capabilities
for predicting, monitoring, analyzing, and optimizing application
performance. For example, 63 percent of Best-in-Class companies use tools
for monitoring web application performance and 48 percent use tools to load
test their web applications.
The report also found that Best-in-Class organizations experienced:
-- 85 percent improved success rates in preventing issues with
application performance before end users are impacted, as opposed to
Laggards who reported zero percent improvement; and
-- 106 percent average improvement in application availability,
compared to Laggards who reported two percent improvement.
"Aberdeen's findings empirically underscore the correlation between
quality web experiences and business success," said Matt Poepsel, Gomez VP
of performance strategies. "For too many businesses, the end user's
experience remains clouded in obscure information -- or no information at
all -- putting business, brand and profits at risk. The Gomez(R)
ExperienceFirst(SM) platform of services helps businesses ensure quality
end user experiences by testing their web applications in development and
measuring them after deployment, mirroring the proactive, lifecycle
approach to managing and improving application performance prescribed by
Aberdeen in this report."
Thursday, July 3, 2008
Use multiple content sections
Take advantage of multiple content sections in your gadget spec to render more tailored views for
canvas and profile pages. This will help ensure that the container only loads the necessary components
for each view. In particular, focus on making your profile view as lean as possible.
Use appData as a cache for content
It's much faster to request data from the container than it is to hit your own server. There are
lots of ways you can cache your application data in the Persistence API and speed up page
loads. The profile view is a great place to do this because it gets a lot of page views
and there is less dynamic content.
Here's the slow way to load a profile page:
1.User opens profile page.
2.Your app uses makeRequest to get data from your server.
3.Once the data is returned, your app renders the profile page.
Here's a much faster way:
1.User opens profile page.
2.Your app uses a DataRequest to get data from the container.
3.Once the data is returned, your app renders the profile page.
4.Now, your app uses makeRequest to get data from your server.
5.Once the data is returned, your app updates the profile page.
An example
First, let's look at using multiple content sections. Here's the bare minimum:
;<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="users <3 speed">
<Require feature="opensocial-0.7" />
</ModulePrefs>
<Content type="html" view="profile">
<![CDATA[
Hello, profile!
]]>
</Content>
<Content type="html" view="canvas">
<![CDATA[
Hello, canvas!
]]>
</Content>
</Module>
Now let's use the technique where we populate the profile view with HTML cached in appData:
<Content type="html" view="profile">
<![CDATA[
<script type="text/javascript">
function request() {
var req = opensocial.newDataRequest();
req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER), "owner");
req.add(req.newFetchPersonAppDataRequest(opensocial.DataRequest.PersonId.OWNER, "profile"), "usrdata");
req.send(response);
};
function response(data) {
console.log(data);
var usrdata = data.get("usrdata").getData(),
owner = data.get("owner").getData(),
profileHtml = 'No data';
if (usrdata[owner.getId()]) {
profileHtml = usrdata[owner.getId()].profile || 'Empty data';
}
document.write(profileHtml);
};
gadgets.util.registerOnLoadHandler(request);
</script>
]]>
</Content>
Finally, implement some functionality for the canvas view. When the user takes an action that
will update the data shown in their profile, update the 'profile' field in appData.
This app lets the user set a quote to be displayed on their profile.
When the 'save' link is clicked, the quote and the HTML to display in the profile view are updated in appData.
Here's the full application spec:
<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="users <3 speed">
<Require feature="opensocial-0.7" />
</ModulePrefs>
<Content type="html" view="profile">
<![CDATA[
<script type="text/javascript">
function request() {
var req = opensocial.newDataRequest();
req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER), "owner");
req.add(req.newFetchPersonAppDataRequest(opensocial.DataRequest.PersonId.OWNER, "profile"), "usrdata");
req.send(response);
};
function response(data) {
console.log(data);
var usrdata = data.get("usrdata").getData(),
owner = data.get("owner").getData(),
profileHtml = 'No data';
if (usrdata[owner.getId()]) {
profileHtml = usrdata[owner.getId()].profile || 'Empty data';
}
document.write(profileHtml);
};
gadgets.util.registerOnLoadHandler(request);
</script>
]]>
</Content>
<Content type="html" view="canvas">
<![CDATA[
<script type="text/javascript">
function request() {
var req = opensocial.newDataRequest();
req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER), "owner");
req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER), "viewer");
req.add(req.newFetchPersonAppDataRequest(opensocial.DataRequest.PersonId.OWNER, "quote"), "appData");
req.send(response);
};
function response(data) {
var viewer = data.get("viewer") && data.get("viewer").getData(),
owner = data.get("owner") && data.get("owner").getData(),
appData = data.get("appData") && data.get("appData").getData(),
quote = '',
text = '';
if ((viewer.getId() || -1) == (owner.getId() || -2)) {
if (appData[owner.getId()]) {
quote = appData[owner.getId()];
}
text = ['Edit your quote: ',
'<input id="quote_input" type="text"/> ',
'<a href="javascript:void(0);" onclick="save();" value="',
quote,
'">save</a>'].join('');
document.getElementById('main').innerHTML = text;
}
};
function save() {
var quote = document.getElementById('quote_input').value,
profileHtml = '';
profileHtml = ['Latest quote: ', quote].join('');
req = opensocial.newDataRequest();
req.add(req.newUpdatePersonAppDataRequest(
opensocial.DataRequest.PersonId.VIEWER, "quote", quote), "updatequote");
req.add(req.newUpdatePersonAppDataRequest(
opensocial.DataRequest.PersonId.VIEWER, "profile", profileHtml), "updateprofile");
req.send(response2);
};
function response2(data) {
if (!data.hadError()) {
document.getElementById("status").innerHTML = "Saved quote at " + new Date();
} else {
document.getElementById("status").innerHTML = "There was a problem updating your profile";
}
/*
* Now that the page is loaded you can use makeRequest to
* see if you have fresher data on your server.
*/
};
function status(text) {
var dom =
dom.innerHTML = text;
};
gadgets.util.registerOnLoadHandler(request);
</script>
<div id="main"></div>
<div id="status"></div>
]]>
</Content>
</Module>
Wednesday, July 2, 2008
Best practices for web development
Many techniques that are used in normal web development will also benefit your OpenSocial app. Here are some of the most effective techniques.
Control the caching on your content
Most containers offer support for the Cache-Control HTTP header. You have server-side control over how your resources are cached, so be sure to set your headers appropriately for maximum benefit
The Cache-Control
header is best described in the HTTP/1.1 specification but there
are some simpler descriptions available as well. If you're not sure about the cache
headers your server is currently sending, you can try some publicly available tools to
examine the cache headers on your files and see if they need to be tweaked.
Be aware that the Cache-Controlheader will be examined for all content coming from
your server, including XML application specs, responses from makeRequest
(both prefetched and not), and proxied images. Be sure to set caching headers for all of this content!
Notes on Apache
Apache defaults to using Last-Modified and ETag headers to control
caching for static files, rather than the recommended Expires and Cache-Control: max-age headers
. If you are using Apache, change your cache headers to Expires and Cache-Control: max-age!
Need to disable caching on your Apache server? Use the following in your .htaccess
file to disable caching on .css, .js, and .xml files (change the
FilesMatch line if you need to support more filetypes):
Header unset ETag
FileETag None
Header set Cache-Control "no-cache"
What are the benefits? Your server has much more control over how the container caches its
content. You can set a low cache expiration for content that changes often, and a high cache timeout for
content that does not change. Caching will become much more efficient once you set the appropriate headers
Reducing the number of fetches
The HTTP/1.1 specification states:
Clients that use persistent connections SHOULD limit the number of simultaneous connections that they
maintain to a given server. A single-user client SHOULD NOT maintain more than 2 connections with any
server or proxy.
For this reason, some internet browsers (like IE7) will only download two files from a given server at a
time, shared amongst all HTML, XML, image, CSS, and JavaScript files. To reduce the number of connections
that a user has to make back to your server, consolidate and inline as much code as possible.
If your JavaScript includes look like:
<code><span style="font-weight: bold;"><script src="http://www.example.com/javascript.core.js" type="text/javascript"></script></span>
<span style="font-weight: bold;"> <script src="http://www.example.com/javascript.extra.js" type="text/javascript"></script></span></code>
then you should combine each file into one master JavaScript file:
Better yet, inline your code if at all possible:
function1() {
...
};
...
This will save server connections for other assets. Remember that this approach can be used for CSS, as well
.
To decrease the number of image files your application needs to load, you can use image spriting to combine
all your image files into a single master "sprite" file. Check out A List Apart's CSS Spriting article
for a good description of this technique.
Generally speaking, concatenating your files is a great performance improvement you can make. Because of the
aggressive caching that containers perform, even using a relatively slow server-side script to
automatically concatenate files will still wind up performing better than separate files (once the
automatically concatenated file is cached). Aim for a single CSS and a single JS file in production.
What are the benefits? This approach keeps the number of server connections low, and reduces the total number
of HTTP requests that each user of your application has to make.
Some other best practices:
1.Turn on gzip for any content you deliver. Good things come in small packages.
2.Minimize JS and CSS. Again, small is good.
3.Split CSS and image files across 2-4 servers. Browsers limit the number of concurrent connections to any one
server.
4.Place JavaScript as late in the page as possible. Loading JavaScript blocks the downloading of other
important components like images and CSS.
Tip: Try the YSlow Firefox plugin to analyze your app's performance.
Latency Tips for Orkut--Orkut-specific techniques
Prefetch data from orkut:
The orkut team has implemented a "pre-fetcher" that will analyze your app and attempt to load the data you need at the same time it's rendering the container page, so when your app sends a DataRequest, the response is almost instantaneous. To get the most out of this feature, follow these guidelines:
Do request data that you will always or nearly always need, even if it's not needed immediately on loading your gadget.
Do batch up multiple request items into one DataRequest.
Don't request data you don't need.
Don't add newUpdatePersonAppDataRequest to your first DataRequest.
Don't call opensocial.requestCreateActivity before sending your first DataRequest.
Preload data from your server:
If your application uses a makeRequest call to fetch data from a third party server, chances are that you've written something similar to:
function request()
{
var params = [];
....
gadgets.io.makeRequest("http://www.example.com/content.html", response, params);
};
gadgets.util.registerOnLoadHandler(request);
While this code is syntactically correct, it isn't very efficient at loading data. Users of your application will need to:
1. Wait for orkut to render your application IFrame.
2. Wait for the IFrame to finish loading so the OnLoadHandler methods will execute
3. Wait for the makeRequest call to return data from your server.
During this time, a slow application will show a loading animation in the best case, or nothing at all in the worst. To address this, orkut will offer additional syntax for preloading content from a makeRequest call while the gadget is being rendered. This feature is enabled through the addition of an extra parameter in your ModulePrefs. If your makeRequest call looks like:
var params = {};
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
gadgets.io.makeRequest("http://www.example.com", response, params);
You can cache the request by adding a tag:
When your application IFrame loads, you will see something similar to the following embedded in the source:
gadgets.io.preloaded_ = {"http://www.example.com":{"body":"...","rc":200}};
Where "..." is the content that exists at http://www.example.com. When your application executes the makeRequest call, this content will be returned instantly, without needing to hit your server again. Signed request calls can take advantage of preloads with a slight change to the preload syntax. If your signed request code looks like:
var params = {};
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
gadgets.io.makeRequest("http://www.example.com", response, params);
The corresponding preload code you should use is:
There are a few more optimizations you can use to make preloads work even better:
1. Turn off sending the viewer in signed requests. If you don't need the VIEWER ID for your signed
request, disable it by adding signViewer="false" to your tag. This will allow orkut to cache your
request for a lot more requests. This is a critical improvement for profile pages!
2. Use multiple tags if you have more than one request. You're not limited to one tag, so preload whatever you can.
3. Restrict preloads to the correct view. If you only use a certain request in a specific view, restrict
the preload to that view by adding a views attribute to your tag. For example, to restrict a
preload to the canvas view, add views="canvas" to your tag. You can also specify multiple comma
separated views, like views="canvas,profile".
What are the benefits? Users no longer need to wait for your application to finish loading on orkut before
executing a makeRequest call. Orkut will make the request and insert the response directly into the
application as it renders your application.
Cache your static content
Orkut will now rewrite the appropriate href or src attributes on HTML elements to take advantage of the
caching proxy, meaning that all non-dynamic references to remote content will automatically get the
benefit of caching.
If your source contains an image tag which looks like:
"
"
Orkut will render the image tag as:
" "
What are the benefits? Users no longer need to wait for your application to finish loading on orkut before
executing a makeRequest call. Orkut will make the request and insert the response directly into
the application as it renders your application.
Cache your static content
Orkut will now rewrite the appropriate href or src attributes on HTML elements to take advantage of the
caching proxy, meaning that all non-dynamic references to remote content will automatically get the benefit
of caching.
If your source contains an image tag which looks like:
Orkut will render the image tag as:
Any HTML fetched using makeRequest or otherwise passed through the proxy will also have its links rewritten
in this manner. Caching is now automatic throughout your entire application.
However, caching can make development difficult, so if you really need to disable this automatic rewriting,
you can use the following code inside the section of your gadget spec:NONE
Keep in mind that this should only be used to help develop your application. Your production apps should not
rely on this feature!
What are the benefits? This approach can dramatically reduce the load on your server for image, CSS, and
JavaScript resources that are directly included in your application source, without you needing to
change any code at all.
Note: Orkut's rewriting is currently not compatible with the element. If you use the element to use relative
paths in your application, you will need to change your code to use fully-qualified URLs.