tags:

views:

380

answers:

3

How to determine if a javascript was already loaded by other html file? I want to reduce the redundant loading of the javascript files to decrease the loading time of my webpages.

+5  A: 

If your web server is providing correct caching headers this shouldn't be necessary, the browser will cache the javascript file across multiple requests.

You might want to check out the YDN page Best Practices for Speeding Up Your Web Site

roryf
Thanks for the YDN and enlightening me on the web server. I am new to this stuff.
That's generally true about the caching, but a fair number of clients don't receive caching headers due to bad proxies, Internet security software, etc. Some studies have estimated that up to 20% of requests don't benefit from HTTP compression and/or proper expires headers due to this header interference. Because of that, it's not a best practice to rely on caching to save you from duplicated requests unless it's your last resort.
Dave Ward
+1  A: 

If you want to prevent the files from being downloaded twice then this will be automatic provided they are set to be cacheable (most webservers should set these headers sensibly by default).

If you want to make sure that the include tag happens only once when including files in a dynamic language then you will need some sort of manager. ASP.NET provides a scriptmanager class that does this (among other things). I cannot speak for other languages and frameworks

Jack Ryan
Thanks for enlightening me on this web server thing. I am new to this stuff so shall catch up with ASP.NET soon.
A: 

As Rory says the second request will probably be cached, and noting that this is a bit of a design failure if it can happen, you can understand that the cached file is still going to execute with negative effect.

This is horrible, but you could wrap your JS script like this:

if (!document.foo)
{
  //your script here

  document.foo = true;
}
annakata
Oh yeah thanks and I shall try this one.