user1123656
user1123656

Reputation: 11

How to load a javascript function once on ajax website?

I have a javascript function that needs to be in content element, and not on header, because of dynamic ajax reload which reloads the main content and not the header.

I'd like to load this javascript function only once per session. I mean that when the user clicks on "page 1", the page loads this specific function, and when he clicks on page 2, then clicks again on "page 1", the javascript function doesn't reload itself.

Is there a way to do that ?

Thanks.

Upvotes: 1

Views: 194

Answers (1)

uadnal
uadnal

Reputation: 11435

Create an object that tracks if the page has been loaded or not

var isLoaded = {
   page1: false,
   page2: false
};

// click...
if (isLoaded.page1) {
   $('#page1').show();
} else {
  $.get('/page1.html', function(html) {
      $('#page1').append(html).show();
      isLoaded.page1 = true;
  });
}

Upvotes: 2

Related Questions