I have a couple of pages on my site where fairly large chunks of text are toggled using JQuery and/or regular Javascript tabs.
At the moment the performance is fine, but I am aware of the potential for degradation as traffic on my site grows. The good part is that 80% of the content of the page isn't visible at the very beginning - the user has to click on something to see the rest of 开发者_开发问答the content.
Is there a way to get the page to display when the 20% is loaded, and have the rest finish loading at its own pace? (FYI I am OK with Javascript but I'm a complete novice at AJAX.) The difference in time is probably a few tenths of a second, but as you know, that can be everything. :)
You can render the main parts of the page on load, and then use Javascript or jQuery make asynchronous callbacks to load the rest of missing parts as hidden html elements.
The easiest way to hook up to the DOM load event that works across browsers is to use jQuery. It's a framework that makes working with JS and the DOM easy. They have some very good tutorials on the Docs page. To execute javascript code after the DOM has finished loading you use
$(document).ready(function(){
// Your code here
});
And to exeute ajax requests you can use the ajax method. The docs do a pretty good job at explaining how it works. Then on the success callback you can use selectors and other methods to hook the response back into the DOM. You have a multitude of choices here append, appendTo, prepend, prependTo, insertBefore, inserfAfter. You can find documentation for the methods on the jQuery site I linked to.
You're on the right track: AJAX is the way to do this. The basic approach would be:
- Move each of the hidden items into its own partial.
- Write a controller action to render each of these partials.
- Inside the main view, use AJAX to call each of these actions and insert the results (i.e., the rendered partials) into the appropriate places in the page.
This last step can occur in different ways. If you're positive that the user will take the action that ends up revealing these partials, you can make the AJAX calls when the page loads (i.e., inside $(document).ready(function(){...});). Or, if you're willing to let the user wait a little longer but reduce the load at the server, you can make the AJAX call when the user takes action.
Sorry I didn't give complete code examples but this should give you the overall strategy (and point you to where to look next).
精彩评论