Search code examples
browserbrowserifybrowser-cachecdn

Cache in browser with browserify


If I am using a CDN to serve .js libraries like jquery or react , to my client through multiple 'script' tags then the browser caches these files and later reuses them instead of requesting them again for faster initial load time.

With browserify all .js libraries are bundled into a single .js file , so won't the client need to download the entire .js bundle every time ? Will this not make the initial load time slow ?

Example ,

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js')>
//get from cache if present
<script src='mycomponents.js'> // should get from server

With browserify ,

<script src='mybundle.js'> // includes jquery + mycomponents , always from server


Solution

  • Depending on the server you are using, it will say to the client's browser if the file can be served from cache or not. Typically, if your script is modified (it means any of the bundled scripts), or when it is the first visit, the client need to request the whole bundle. If not, it will send 304 a status code, saying that cached file can be used.

    If you use CDN, the client most likely don't need to download all the dependencies, since he probably has cached them when visiting other websites. On first visit, or when it's updated, the only file to download is your components' script, which will probably be updated more often, or cache will expire sooner.

    Browserify is good for productivity and dependency management. If you're looking for performance, I would recommend using CDN.

    But remember that a CDN can fail, so prefer using a failover script on your server

    <script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
    <script>if (typeof jQuery === "undefined") { document.write('<script src="assets/js/jquery.min.js">\x3C/script>') }</script>