views:

450

answers:

1

I'm a bit new to the Ajax thing and am hoping you all can suggest which of these two methods is most efficient. Both approaches seem to work, but perhaps there is some better way altogether?

thisPage.html wants to display a blob of html drawn from thatPage.html (on the same host) in response to a click on a link. I'm using Shadowbox's html player to display the blob, and I'm using jQuery's get() as a shortcut to the XMLHttpRequest.

In my first solution, thisPage.js contains this function:

function loadEntry(entry){
  jQuery.get('thatPage.html', function(data){
    var elem = document.createElement("div");
    elem.innerHTML = "<div class='entry-to-show'>" + jQuery(data).find("a[name='" + entry + "']").parent().parent().html() + "</div>";

    Shadowbox.open({
      options: {
        enableKeys: false
      },
      player: 'html',
      content: elem.innerHTML
    });
  });
};

But then I thought, rather than have thisPage load thatPage every time loadEntry is called, I'd just call it once when thisPage.js is loaded, wrap it up as a variable containing a jQuery object and access it like this:

var $Content = null;

jQuery.get('thatPage.html', function(data){
  $Content = jQuery(data).find("#content");
});

function loadEntry(entry){

  elem = $Content.find("a[name='" + entry + "']").parent().parent().html();

  Shadowbox.open({
    options: {
      enableKeys: false
    },
    player: 'html',
    content: elem
  });
};

Is this second method actually more efficient, or is there some other approach that would be more appropriate for what I'm trying to do? Any advice or general observations would be welcome.

Thanks, jjon

A: 

Your second approach is definitely more efficient. Without knowing more about what problem you're actually trying to solve by loading information from one page to another I can't provide a better solution although I can't think of any instances where what you're doing would be an inappropriate solution.

Cryo
I appreciate your response. The problem I'm trying to solve, now solved I guess, is that thatPage presents a body of information in a stand-alone page, but I needed to present bits of it in context on thisPage. I didn't want to pull in the whole of thatPage with all of its formatting and design by using .load() and an iframe or something like that. The data is only in html, rather than in a database or some other silo and this approach seems to (almost) work. It still has one little wrinkle that I've yet to iron out which I'm now posting as a separate question.
jjon