Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: How to download JS asynchronously?

On my web site, I'm trying to accomplishes the fastest page load as possible.

I've noticed that it appears my JavaScript are not loading asynchronously. Picture linked below.

alt text http://img249.imageshack.us/img249/2452/jsasynch2.png

How my web site works is that it needs to load two external JavaScript files:

  • Google Maps v3 JavaScript, and
  • JQuery JavaScript

Then, I have inline JavaScript within the HTML that cannot be executed until those two files above are downloaded.

Once it loads these external javascript files, it then, and only then, can dynamically render the page. The reason why my page can't load until both Google Maps and JQuery are loaded is that - my page, based on the geolocation (using Gmaps) of the user will then display the page based on where they are located (e.g. New York, San Francisco, etc). Meaning, two people in different cities viewing my site will see different frontpages.

Question: How can I get my JavaScript files to download asynchronously so that my overall page load time is quickest?

UPDATE:

If I were to download, somehow, Google-maps and JQuery asynchronously, how would I create an event that would be fired once both Google-maps and JQuery have downloaded since my page has a hard dependency on those files to execute.

UPDATE 2

Even though there are 3 answers below, none still actually answer the problem I have. Any help would be greatly appreciated.

like image 225
Teddyk Avatar asked May 10 '10 14:05

Teddyk


People also ask

Does JavaScript run asynchronously?

JavaScript is a single-threaded, non-blocking, asynchronous, concurrent programming language with lots of flexibility.

How do I download a .JS file from URL?

open the Js script link and press ctrl+s i.e save it. Save it by any desired name and then copy it your project folder and then include it in your project files where you have included other files like jquery and css.


1 Answers

HTTP downloads are generally limited by browsers to two simultaneous downloads per domain. This is why some sites have the dynamic content on www.domain.tla and the images and javascript on static.domain.tla.

But browsers act slightly differently with scripts, while a script is downloading, however, the browser won't start any other downloads, even on different hostnames.

The standard solution is to move scripts to the bottom of the page, but there is a workaround that might or might not work for you: Insert the script DOM element using Javascript.

like image 52
Esteban Küber Avatar answered Sep 21 '22 23:09

Esteban Küber