Maximizing Efficiency on the Frontend: Balancing Requests with Caching

I am currently tackling a large website that has accumulated quite a bit of technical debt that needs to be addressed. The site contains a significant amount of JavaScript and CSS files being loaded. Currently, these files are aggregated and minified in layers, with one layer being used on each page, while other layers are only loaded on specific pages that require them.

For instance:

page 1:
    - default.css
    - page1.css
    - some-feature.css
    - default.js
    - page1.js
    - some-feature.js

page 2:
    - default.css
    - page2.css
    - default.js
    - page2.js

page 3:
    - default.css
    - page3.css
    - some-feature.css
    - some-other-feature.css
    - default.js
    - page3.js
    - some-feature.js
    - some-other-feature.js

In addition to these resources, there are numerous external resources being loaded for tracking, advertising, social integration, and more.

I have a hunch that these resources could load faster (both initially and in subsequent requests) if they were combined and minified into one single JS and CSS file per page. For example, page1.css + page1.js, and on another page it would be page2.css + page2.js. However, this approach may result in certain content being loaded redundantly (such as the original default.css).

What is the recommended method for loading these resources efficiently? And do you have any test results regarding this approach?

Answer №1

TLDR: The benefits of caching are clear, as it helps your page load faster with a compressed payload

In many projects I've observed, all front-end assets were combined into single files for efficient caching. Utilizing gzip compression can significantly reduce file sizes.

Consider incorporating small amounts of CSS directly into your HTML for page-specific styles.

When it comes to JavaScript, converting assets into AMD modules and using tools like RequireJS can streamline dependency management and execution order.

Inlining smaller snippets of JS code can also help reduce overall package size.

Excessive advertising can be detrimental to user experience, so loading banners asynchronously (check out postscribe) is recommended.

Take advantage of PageSpeed Tools by Google for easy optimization tips for your website's payload.

Answer №2

Here are a few queries you might have:

  1. Should I combine and minify my files or schedule them for subrequests?. When deciding on this, consider the size of the compressed and minified .js file. It's advisable to aim for a file size lower than 300kb (even less on mobile devices). If all your pageX.js files add up to 100kb, it's best to combine them. However, if your files exceed 300kb per page, continue reading the section on significant js assets below.

  2. What should I do about duplicate default.css/js Code? Keep them separate but host them on the same URL. By doing so, the browser can cache the URLs and avoid reloading the files unnecessarily (also refer to http expiry header for better caching). It's also recommended to store them on a fast, replicated external location (such as Amazon Cloud Front / S3).

Recommendation:

common (externally hosted, same url): 
- default.minified.css
- default.minified.js

page 1:
- page1.css
- page1.js

page 2:
- page2.css
- page2.js

page 3:
- page3.css
- page3.js

** Dealing with Large JS Assets **

If your page3.js file grows significantly (>500kb), consider implementing lazy loading. This involves loading the core functionality required for user interaction first.

There are various methods to asynchronously load single javascript files (search for "lazy loading javascript" on Google) for each library. For example, you can use jquery to dynamically load a javascript file like this

$.getScript('tinymce.js', function() {
    TinyMCE.init();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue app showcasing array items through search upon button pressing

As I delve into learning Vue Js, I've encountered a bit of confusion. My goal is to showcase array elements from a Rest API based on the specific ID being searched for. For example: within my Json File are various individuals with unique IDs, and when ...

Tips for modifying the status of a single component within a v-for loop without impacting other components

I am encountering an issue with my childComponent that is dynamically rendered using v-for within the parentComponent. The Parent component contains logic to fetch data from the database and display it on the screen. The fetch request query is dependent on ...

Border extends across two separate rows

Let me illustrate my issue with a specific example where I am utilizing a single column with a rowspan: <table border="1" style="width:300px"> <tr> <td rowspan="2">Family</td> <td id="jill">Jill</td> <td>Smi ...

Issue with Vue 2: Promise does not resolve after redirecting to another page

Although I realize this question might seem like a repetition, I have been tirelessly seeking a solution without success. The issue I am facing involves a method that resolves a promise only after the window has fully loaded. Subsequently, in my mounted h ...

Differences between $.ajaxPrefilter() and $.ajaxSetup() in jQuery Ajax

During my exploration of ajax in jQuery, I encountered two terms: $.ajaxPrefilter() and $.ajaxSetup(). It seems that both of these terms are related to making modifications to AJAX operations before they are executed or called by $.ajax(). Could someone p ...

Continuously decrease a sequence of identical numbers in an array through recursion

One of the key challenges was to condense an array of numbers (with consecutive duplicates) by combining neighboring duplicates: const sumClones = (numbers) => { if (Array.isArray(numbers)) { return numbers.reduce((acc, elem, i, arr) => { if ( ...

Prevent Symfony2 Twig from rendering HTML content

Is there a way to disable the rendering of HTML responses in Twig? I am currently working on a RESTful API and my goal is to completely prevent HTML rendering. For instance, if I access /foo/bar without an oAuth Access Token, Symfony2 should reply with a ...

Tips on incorporating Prisma model into prisma-offset-pagination

I am currently implementing pagination using the prisma-offset-pagination package. To do this, I need to utilize Prisma Model in my code, but I'm unsure of the correct approach: Refer to line: 02 const result = prismaOffsetPagination({ model: user ...

JavaScript does not function properly when interacting with the result of a POST request made through $.ajax

Question: After including jQuery files and functions in index.php, do I also need to include them in select.php? To clarify my issue, here is the problem I am facing: Initially, I am trying to send data to select.php using jQuery's $.ajax. The data ...

Unveiling the mystery: Locating the position of an element within a multidimensional array using JavaScript or JQuery

How can I retrieve the index of a specific element in a JSON array converted from a PHP array using json_encode, using JavaScript or JQuery? Initially, the user will choose an option where the values correspond to people's IDs. <select class="for ...

Tips for preventing multiple requests in your JavaScript search autocomplete feature

I'm currently using the Turbolinks.visit action with the help of $(document).on("input");... HTML <form id="mainSearch" method="get" autocomplete="off"> <input type="search" name="s" placeholder="Search" /> </form> Javascript ...

Incorporating information collected from a modal form into a table using vue.js

insert code hereThis single page application allows users to input data into a modal, which is then automatically added to a table on the main page. var modal = document.getElementById('modalAdd'); var modalBtn = document.getElementById(' ...

Prevent users from selecting elements on the mobile site

Hey there! I'm currently working on preventing users from selecting items on my mobile site. While I've been successful in doing so on a regular website using the CSS class below .unselectable { -moz-user-select: -moz-none; -khtml-user-s ...

Troubleshooting issue with jQuery subtraction not functioning as expected

Everything seems to be functioning correctly except for the subtraction operation. function add_culture(ele) { total=parseInt($('#total_price').val()); culture_price=parseInt($('#culture_price').val()); $(& ...

Default Value for Null in Angular DataTable DTColumnBuilder

What is the best way to define a default value in case of null? $scope.dtOptions = DTOptionsBuilder .fromSource('api/Restt/List'); $scope.dtColumns = [ DTColumnBuilder.newColumn('modi ...

Storing past entries in a local storage using JavaScript

Currently, I am developing a JavaScript program that involves 3 input boxes. The program is designed to display whatever is typed into each input box on the page. To store and re-display previous submissions, I have implemented local storage. However, I en ...

Perform two functions in order using jQuery within a loop

Just dipping my toes in the waters of Javascript. Please go easy on me :) I'm working with two functions that both involve making jQuery requests within for loops. Here's an example: function x(y,z) { for (var i = 0; i < y; i ++) { $.a ...

When using this.$refs in Vue, be mindful that the object may be undefined

After switching to TypeScript, I encountered errors in some of my code related to: Object is possibly 'undefined' The version of TypeScript being used is 3.2.1 Below is the problematic code snippet: this.$refs[`stud-copy-${index}`][0].innerHTM ...

What is the best way to modify React state?

Can someone help me troubleshoot an issue with toggling React state after a button click? I want to be able to change "Work From Office" to "Work From Home" and vice versa, but it's only working once. Is there a way to achieve this using an if stateme ...

What could be causing JSON.parse to encounter errors when parsing a string array?

Within the following function, I am utilizing JSON.parse() on specific string arrays saved in window.sessionStorage. This allows me to apply methods like .map(). window.sessionStorage = { myArray1: "["805746|search|4","980093062|search|0","980113648| ...