开发者

Best Performance + jQuery Ajax + Div Refresh

Does anyone have good suggestion of the best option for jQuery Ajax to refresh a DIV?

F开发者_JAVA技巧ollowing are what I'm trying to achieve:

  1. Optimization of performance is emphasized.
  2. There will be navigation on the left just like Google+/Facebook, on the right, there will be content pane (DIV).
  3. When user clicks on each navigation, the content pane will refresh accordingly without refreshing the whole page.


Use different methods on the server that generate each section of content. That way you can simply call that method to get that specific content rather than calling a generic method and extracting just the content you need. Once you have distinct methods to get each content item, you can use the href to that method as the link and use the jQuery load method to retrieve the content via AJAX and update the content area.

The following example assumes each of your navigation links has the class nav-link and that the content area has id content. It also assumes that you've included jQuery.js.

 <div class="menu">
     <ul>
        <li><a href="/foo" class="nav-link">Foo</a></li>
         ...
     </ul>
</div>
<div id="content">
    ... initial content...
</div>

<script type="text/javascript">
 $(function() {
     $('.nav-link').click( function() {
        var href = $(this).attr('href');
        $('#content').load( href, function() {
            // you can do something here after the content is loaded if needed
        });
        return false; // don't actually follow the link
     });
 });
</script>


With an ajax call the majority of your overhead is going to come from the XHR request itself. Though you can cache your necessary objects in variables to increase performance as much as possible. Assuming your HTML is like this:

<ul id="nav">
    <li><a href="content1.html">Link 1</a></li>
    <li><a href="content2.html">Link 2</a></li>
</ul>

<div id="contentpane"></div>

You could then use the following JS

$(document).ready(function() {
    // Load our DOM objects into vars
    links = $('#nav a');
    contentPane = $('#contentpane');

    // On click load content into pane using ajax
    links.click(function(e){
        contentPane.load( $(this).attr('href') );
        e.preventDefault();
    });
});


$.ajax({
  url: <YOUR_POST_URL>,
  success: function(data) {
    $('#divId').html(data);
  }
});


Have one page which includes the menu, and separate pages for all pages you would like to display (without the menu). On a menu item click, send an AJAX request to get the appropriate page (full page html will be returned) and just set that as the html of your div. Just watch out for duplicate element ids/names ans this could cause javascript problems if you aren't careful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜