Load js files from the web or serve them yourself?

62 views Asked by At

I have had this question for awhile and am surprised that I have yet to come across a good/complete answer to it.

The question is essentially this: When it comes to loading js files, in what situations should you load them from the web if available versus serving them up yourself? What case typically allows for the lowest latency?

E.g.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

vs.

<script src="js/jquery-1-11-3.min.js"></script>

2

There are 2 answers

3
Chris Sobolewski On BEST ANSWER

Complete answer: Both.

Loading it off of the web will benefit you in a couple of ways:

1) There is a limit to the number of maximum open HTTP requests a browser can have. However, this limit is per domain. So reaching out to google's servers will not prevent you from loading your CSS/images.

2) It's very likely that the user will already have that file cached, so they will get an HTTP 304 not changed response, and not have to download the file.

Now, with that said, sometimes the server will be down, or network issues will otherwise stop you from loading that file. When that happens, you need a workaround, which we can do like so:

<script>
if (typeof jQuery == 'undefined') {
    document.write(unescape("%3Cscript src='/js/jquery-2.0.0.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>

Put this tag AFTER loading JQuery from the CDN, if the load failed, jQuery will be undefined and proceed to load it from the local source. If the load from the CDN worked, then this block will be skipped over.

1
cari On

Including from own server pros:

  • Technically google servers can be down, and your website won't load correctly.

  • people, that dont trust google and have it blocked, script blocked etc. These ppl too wouldnt want to include the file from google directly.

  • connections to google can have higher latency. if you have your audience in your own country and a good provider, your connec can be faster than googles.

contra:

  • higher webserver traffic

  • more connections

  • higher CPU impact

You have to decide for yourself, which one is better for you. For smaller sites I'd go for local stored file.