tags:

views:

81

answers:

4

Is calling functions in different JavaScript files slowing down JavaScript processing by the browser?

In other words, can I call functions from a file to another one? Or would it be better to call function in the same file?

+4  A: 

It makes no difference at all. Regardless of which script file the code comes from, it gets intepreted into the document's context, which is the same for all of the script files and inline script on the page.

You can test it with this incredibly sloppy script: http://jsbin.com/uxiye

Somewhat off-topic, but some of the other answerers are absolutely right to point out that while there's no difference executing the functions, there can be a big difference in script load time... You didn't ask about page load time, but still, worth pointing out.

T.J. Crowder
+2  A: 

As long as they're all loaded, this is standard functionality and does not result in a performance penalty.

Fosco
+2  A: 

From execution point of view there is no difference.

But remember that loading one all-in-one JS file is faster than many JS files - server needs to be asked only once for first one.

gertas
This is not true. Browsers can download multiple files at once, so if split a 1MB file into 2 500KB files, you will transfer them simultaneously, effectively cutting transfer time by 40 - 50%
Mike Trpcic
Why -1? If you split 1MB file into 2x500KB then you still need to send 1MB, if connection is 1mbps then it means ~8s in both cases (no magic time cutting). Tell me why Google uses image sprites with all images packed in one? In your case the second connection must be opened (SYN roundtrip) and server queried, gzip initialized - additional cost. Also browser allow to open max 2 connections to same host - probably 1st one will be occupied by HTML, CSS or IMGs. Also to evaluate JS browser must finish loading all JS files. More JS files make sense in case of later lazy loading.
gertas
@Mike I see that you are familiar with Rails so I think that you should familiarize with http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html section **Caching multiple javascripts into one**. They wrote it for some good reason.
gertas
Why the downvote? Perfectly reasonable answer and observation.
T.J. Crowder
A: 

Well, script tags block each other, so they're not all downloading at once. For that you need to do async loading

Secondly, you have to deal with the round-trip calls to the server(s) to get the files and take the latency hit for that.

Lastly, you get to parse and execute code. Assuming you have no duplicate functions they will parse the same and execute the same.

So yes, it's slower, but not because of JavaScript, it's because of HTML and the network. See Steve Souder's site or his book(s) on performance.

AutoSponge