tags:

views:

53

answers:

3

Hi!

I have coded a page that has two div one beside the other. The first one serves as a nav tree that, when clicked, loads a page in the right div with AJAX. I have to include a javascript file when one of the page is loaded.

I have managed to do jsut that and all works perfectly but each and every time that someone want to see the page, it includes the corresponding javascript page. This seems to me as a major leak and I am not so familiar with javascript development.

Question: Is there a way, when including the js file, to ensure that it was not previously included?

A: 

Include the javascript in the main page HTML, not the page being loaded.

Andrew Johnson
Yes, but in that case that would'nt be specific to the page loaded which is the base principle of the application.
Balls-of-steel
You have to ask yourself... how big are these javascript files. I assume if you concatenate and minify your javascript, then you should load it all in the first view, not piece by piece. Your application will be more responsive and hit your server less.
Andrew Johnson
+1  A: 

You could store the names of already loaded scripts in an array, and every time a load is requested, test if the script exist in the array or not.

You could alternatively attempt to check the src's of your script elements, if you load new scripts by appending new script elements into the document. Personally I've had some problems with that approach though.

Jani Hartikainen
A: 

If you don't expect the page to be loaded overly much, you might get away with a guard inside your JS file to prevent redefinition:

if(typeof thisfilehasbeenincluded === "undefined")
{
    var thisfilehasbeenincluded = true;
    //rest of the file goes here
}
DDaviesBrackett