user3598304
user3598304

Reputation: 1

How to prevent javascript to be loaded multiple times

I am in middle of a problem. I have made an application in which I have assigned DIV to be loaded by ajax. Each of the DIV corresponds to a specific module (like one module related to product details, another DIV related to pricing and availability ). Each module is a URL.

DIV1 --- for product details DIV2 --- pricing DIV3 --- catogorisation

All these DIVs are asynchronously loaded. In category module, i have special javascript control for category browsing as a tree view.

The problem I am facing, if I place javascript library in the main page, the control does not show up. and If i place the library in DIV3's URL source page, then it loaded multiple times and hangs my application.

My question is how I can prevent this library to be loaded multiple times if user refreshes the DIV again and again.

Or if it seems a design issue, can you please give your suggestions for proper design. I am keen to know how to unload the library. I am java programmer and thinks in that way. I may have some wrong understanding of javascript working

Thanks in advance
Jujhar

Upvotes: 0

Views: 1222

Answers (1)

Will Reese
Will Reese

Reputation: 2841

Javascript code doesn't have to be executed only when you load a script tag. If you just put the relevant code in a function and call it from the success callback in your ajax function, you can easily avoid this problem.

  1. Move <script> to html body
  2. Wrap relevant code in function

Javascript

function myFunction() {
  //... your code
}
  1. Call myFunction in your ajax success callback

Ajax

$.get("/url", function(data) {
  //add div to page
  myFunction();
});

Upvotes: 1

Related Questions