views:

131

answers:

1

Sorry the title isn't great, it's sort of a loaded question.. What I am trying to do is load multiple pages from links on a page (they are on the same host). In my case it is a forum in the thread view, and I'd like to load the last page of posts so there's some kind of preview.

To keep it simple, my code example assumes jquery is already loaded.

Basically the code is working, however if there's many multiple requests, the page just hangs, ie - if I change the condition to intIndex < 3 or more.

    $('.lastposter').each(
        function (intIndex){
            if(intIndex < 2){
                var threadlink = $('a', this)[1].href;
                var thread = $.ajax({ type: "GET", url: threadlink, async: false }).responseText;

                $(this.parentNode.parentNode).attr('title', $('.post', thread).text());

            }
        }
    );

So then my loaded question is, is there a better way to do this? I was thinking I just need some kind of pause in the loop, or maybe change it so the ajax request happens on (for example) the hover event of the row. Also, will the results be cached? If not, is there a way to make them cached or should I just leave it up to the server? I was thinking to store them as a GM variable (GM_setValue), but maybe that would get messy and or leaky.

If you have some ideas, suggestions, examples etc, I'd be happy to hear about them.

+1  A: 

The problem with your code is, that it requests a non-asynchrous request. This results in the $.ajax function waiting for the servers answer.

For an asynchrous request, you'll need to define a callback function, like this:

$.get(threadlink, function(thread) {  
    $(this.parentNode.parentNode).attr('title', $('.post', thread).text());  
});

To process the links one by one, instead of a bunch of simulaneous requests, you could capture the nodes in an array (makeArray) and pop one at a time at a specific rate (setTimeout/setInterval). Note that greasemonkey got some pitfalls here...

Results will be cached mostly like any other page. IE won't retrieve it before expiration date. Maybe you have to alter the servers cache/expire response headers.

Take a look at this, it sounds similar (but does not use jquery)

http://userscripts.org/scripts/show/19613

Wikser
Thanks for the info, I guess I'm not that clear what the async bit does. I tried your method just now (the callback) and it seems okay if I just log the response but I can't set the title with that (I think this goes out of scope?). Anyway, I'll keep on plugging away with it, but it's clear I'm out of my depth :D
aland