Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it wise to place .css and .js files on a CDN?

It seems like most people use a CDN for placing images and/or videos. Is it wise to place your js and css on a cdn as well?

like image 777
user384708 Avatar asked Jul 06 '10 15:07

user384708


People also ask

Should I combine CSS and JS?

Combining CSS/JS files reduces the number of page requests, in turn reducing the number of round trips made to your server so that other resources can be retrieved faster. With HTTP/2, this is less of an issue as the protocol allows multiplexing, which allows requests and responses to be processed in parallel.

Where do I put CSS and JS files?

The typical answer is: Add JavaScript code by the end of the </body> tag and. Add CSS code in-between the <head> tags.

Can you mix CSS and JavaScript?

No, you can't combine js and css into one file.


2 Answers

While it's a good idea in principle, always have a backup.

With Javascript, if the CDN goes down or the client can't access that js for some reason, then having a local copy as backup will keep your site flexible.

For example, with jQuery, you can have the best of both worlds with this snippet:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined')
    document.write(unescape("%3Cscript src='/scripts/jquery-1.4.2.min.js' type='text/javascript'%3E%3C/script%3E"));
</script>

source and more info

like image 68
Armstrongest Avatar answered Oct 04 '22 08:10

Armstrongest


I believe so. However, if either is dynamically generated you will want to place a relatively low ttl (time to live) on the files so the CDN knows to pull fresh copies. However, if they are not, I would think that dumping them onto Amazon's S3 would be fine.

One caveat - make sure you have an easy way to test and develop without using the CDN as cacheing can be a headache during this process.

[edit]
After some more experience, I believe it's best to version these files and then update their references w/i whatever generates the views.

For example:

style.20111112.css
shoppingcart.20111113.js

This clears the need to have super low ttl's and purge the CDN of the cached copies.

like image 21
Josef Salyer Avatar answered Oct 04 '22 07:10

Josef Salyer