简体   繁体   中英

jQuery load/dynamic content best practise

We have a web app, which is tab structured. When a user clicks a tab for the first time, it loads in content via .load(). This is great and works well and is relatively fast, however we want to cache the load so in future, if the user clicks the same tab as before, it doesnt load the content in, it just .show() the same content as before.

For example:

$('#link1').click(function(){ 
    $('#holder1').load('/pages/link1');
}

How can i store that the user has loaded the content in and just show the content on next click. I need to keep it as modular and universal as possible, so not just link1, link2 etc...

Any ideas?

mmmm....

you should create an array q dictionary on your JS which is like this :

userId LinkId Content

each load you should put the value in there

and the next time you need to load something - check it first on the dictionary / qarray.

You can keep a flag if data is loaded, then check flag again to avoid reload, I am using custom attribute(data-) here.

$('#link1').click(function(){ 
 if($('#holder1').attr('data-loaded')!='yes')
 {
    //data is not loaded then load
    $('#holder1').load('/pages/link1');
    $('#holder1').attr('data-loaded','yes')
 }else
 {
    //data is already loaded then just show or do something else
 }
}

Just to throw out another thought, if your dynamic information is being loaded, say, into the DOM or populating some HTML on the page, you can simply test to see if that HTML exists prior to making your AJAX call to populate it! Consider the case of tabs, where clicking on "#tab2-link" populates "#tab2" and activates it:

$('#tab2-link').click(function() {
    tabLoader(this.id.split('-link')[0]);
});

function tabLoader(tabId) {
    var $tabId = $(tabId);
    if($tabId.html() === '') {
        $tabId.html('<img src="spinner.gif" />'); //Add/show a spinner
        $tabId.load(...); //Remove/replace your spinner on AJAX success.
    }
    $tabId.show();
}

This I would say is the most common approach to this sort of thing, and by far the easiest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM