1

I understand for assets like images, there is a src associated with them, which means that a browser will check the expiration date of that asset before making a new request for that asset at the src to download that asset again and then render it onto the page. How does this work with a script or module such as React? If it is a CDN, does the browser first download the script and then run it the very first time it encounters the script? And then every time after that when it needs this script again, does it just load it from its cached (instead of downloading it again from the source) and running it? Is this the same thing that happens if you have React as a node module?

stackjlei
  • 9,485
  • 18
  • 65
  • 113

1 Answers1

1

This is a very large topic, the basic answer is that browsers will cache assets how you tell them too. You mention that images have expiration dates, these dates are set in HTTP headers sent by the server. You can set the same headers for javascript and any other files you request from a server and the browser will cache them the same way.

After a javascript asset is fetched (from the server or the cache), the browser parses and runs your javascript.

Node modules live in node land. Usually, before you can use code in node_modules in the browser you run it through a tool like webpack or browersify. These tools bundles ALL the code (your application + react + whatever else) into one file (usually), which is then served to browser. The browser doesn't know anything about node_modules. It just parses and runs the javascript you provided.

The one bundled file is cached based on the headers it was sent with. A CDN is (basically) just a special server optimized in serving assets quickly.

Joe Ruello
  • 1,196
  • 8
  • 4
  • Thanks! So would I be correct in saying that regardless of caching, all assets (images & scripts) have to be run each time you go to a different URL, even if they're pages from the same host? For example, if you need a duck image and react script to run when you visit www.examplepage.com/cups and the exact same assets when you visit www.examplepage.com/cup/1, would those assets be run twice? – stackjlei Feb 06 '17 at 16:18
  • 1
    Correct! If you think about it, javascript needs to be run to actually do anything. Even registering event listeners and such needs to start from some kind of imperative procedure. – Joe Ruello Feb 06 '17 at 23:02