I have a web app with an index page and an app page. The user is redirected from the index page to the app page when they start using it.
Right now on my index page I'm using script tags with the defer attribute for Javascript files that will be used on the next page.
I'm doing this so that as the user lingers on the index page for a few seconds, the Javascript files with the core functionality for the app page will be loaded in a way that doesn't block rendering and then they will be pre-cached in the browser for use on the next page.
Is what I'm doing pre-caching the Javascript files without blocking rendering or the page being interactive? Then when the user goes to the app page, the Javascript files are ready to go and they don't have to be downloaded, therefore speeding up performance?
If what I'm doing is correct, is this the "professional approach" a web developer would take, or is there a "right" way?
Index Page (https://example.com/):
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Index Page</title>
<script defer src="/assets/main.js"></script>
<body>
<div>
<h1>This is the index page</h1>
<a href="/app">Click here to go to the app page</a>
</div>
</body>
</html>
App page (https://example.com/app):
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>App Page</title>
<script async src="/assets/main.js"></script>
<body>
<div>
<h1>This is the app page</h1>
</div>
</body>
</html>
CodePudding user response:
This concept is valid and will trigger the browser to load and cache the script. You could do something similar for CSS and images as well.
There is a more modern approach in Progressive Web Apps (PWAs). With a progressive web app you have a cache specific to your web site, and shared between all pages of your web site and have complete control over it.
With this method you can use a script to pre-load the cache with all of the assets necessary. The a second function in the same script can be triggered on every fetch, before it goes to the network or browser's cache. Here you can check your PWA's cache and return that object immediately.
The PWA Cookbook does a nice job of explaining the entire concept. The part most revelant to what you're doing is service workers which discusses both the pre-loading mechanism and intercepting the fetch method.