Storing images in the browser cache is the most efficient method for loading images

As I load multiple images for different breakpoints (desktop, tablet, mobile) and cycle through them using `ng-repeat`, the unnecessary loading of all three image elements at once has become an issue:

<img ng-repeat="img in module.imgs" src="{{img.src}}" class="image-{{img.type}}" style="top: {{img.pos}}px">

This indiscriminate loading is evident in the network requests:

desktop.png GET 304 png angular.js:3151 243 B   4 ms    
tablet.png  GET 304 png angular.js:3151 243 B   5 ms    
mobile.png  GET 304 png angular.js:3151 243 B   3 ms    

In an attempt to optimize this process, I decided to only load the image corresponding to the current breakpoint:

<img src="{{image.src}}" class="image-{{image.type}}" style="top: {{image.pos}}px">

    $scope.$watch($scope.getWindowDimensions, function (newValue, oldValue) {
        $scope.windowHeight = newValue.h;
        $scope.windowWidth = newValue.w;
        $scope.image = null;

        if ($scope.windowWidth >= breakPoints['desk']) {
            $scope.image =  $scope.module.imgs[0];
        } else if ($scope.windowWidth >= breakPoints['mid']) {
            $scope.image =  $scope.module.imgs[1];
        } else {
            $scope.image =  $scope.module.imgs[2];
        }

    }, true);

However, every time the breakpoint changes, a new request is made even though the images have already been loaded:

desktop.png GET 304 png angular.js:3151 243 B   4 ms    
tablet.png  GET 304 png angular.js:3151 243 B   5 ms    
mobile.png  GET 304 png angular.js:3151 243 B   3 ms    
tablet.png  GET 304 png angular.js:3151 243 B   4 ms    
mobile.png  GET 304 png angular.js:3151 243 B   5 ms    

I'm looking for a way to cache or store these images so they are loaded only when needed.

Here is the data structure of the controller:

$scope.module = {
            imgs: [
                {
                    type: 'desktop',
                    src: 'img/desktop.png',
                    pos: 0
                },
                {
                    type: 'tablet',
                    src: 'img/tablet.png',
                    pos: 0
                },
                {
                    type: 'mobile',
                    src: 'img/mobile.png',
                    pos: 0
                }
            ]
        };

Answer №1

When the server responds with a 304 status code, it indicates to the browser that the image has not been modified since the last visit, allowing it to avoid downloading the image again.

To enhance this process, you can include caching headers along with the image, preventing the browser from initiating an HTTP request for the image if it is already cached.

Answer №2

If you want to optimize the caching on your server, consider implementing a caching directive like the one below:

<FilesMatch "\.(png|jpg|json)$">
    FileETag None
    <ifModule mod_headers.c>
        Header unset ETag
        Header set Cache-Control "max-age=604800, public"
    </ifModule>
</FilesMatch>

By setting a long caching duration, you can efficiently cache images. Just remember to update the image name when its contents change or adjust the cache-control value accordingly (in seconds).

With this setup, the browser won't need to request a newer version of the cached image, eliminating the need for a "304" request.

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

Incorporate sliders into Dat.gui for every item within the array

Looking for assistance with adding sliders to a JavaScript object that contains various parameters. var settings = {bgColor: 0x5886a0, ambientColor:0xffffff, opacityCS:[ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], whiteThreshold:[160,160,160,160,160,160] }; I ...

"Troubleshooting a problem with the jQuery AJAX code to verify the existence of an email in the

My implementation involves using jQuery, AJAX, PHP, and MySQL to validate if an email provided in a form is already present in a database. Below is the jQuery code snippet I am currently using: $.post('check-email.php', {'suEmail' : $s ...

Variable defined in one function is not recognized in another function

Currently delving into the world of react.js, I found myself faced with this code snippet: function App() { let Submitable; const [values, setValues] = useState([]) //... onTicket.save = () => { console.log(Submitable) // logs undefiened ...

A step-by-step guide on merging a custom-designed static landing page seamlessly into the root route using ui-router

Working on an angular js 1.x application using ui-router has presented me with a challenge, as I am still new to angular js. Please excuse my ignorance if my question sounds silly. The Issue: I have a main angular js app with its own css and script files ...

The latest update of NextJS, version 13.1.4, encounters issues when implementing SCSS support with the error message "Module next/dist/compiled/sass-loader/fibers.js not

After setting up a new NextJS project, I decided to incorporate SCSS support. The guidelines provided in the documentation seemed straightforward. Following the installation instructions and including an import of SCSS as shown below: import "@/styles ...

The issue of AJAX not being triggered a second time when a button is clicked using a jQuery click event

Whenever I click the button, an AJAX call is triggered to submit a form. The first click works fine and displays an error message if needed. But when I try clicking the button again, the AJAX call doesn't happen. However, if I replace the AJAX call wi ...

Accessing individual .env files defined in the package.json

"begin:development": "set NODE_ENV=development&&nodemon ./bin/www", "begin:testing": "set NODE_ENV=testing&&nodemon ./bin/www", I am managing two unique .env files named dev.env and test.env. My goal is to utilize dev.env when running npm ...

Sharing AngularJs controllers between different modules can help streamline your

I'm facing an issue with trying to access an array from one controller in another controller. Despite simplifying the code for clarity, I still can't seem to make it work. Here is my first controller: app.controller('mycont1', [' ...

Refreshing $scope variables within a function

$scope.myVar = cheese; function please(){ $scope.myVar = "New Value"; } google.maps.event.addListener(marker, 'click', please); This scenario is perplexing to me. I have a variable called "cheese" in the HTML and I anticipated that clicking ...

Troubleshooting: Problems with Initializing Angular UI Select2

I'm having trouble setting up the Angular UI Select2 module. I attempted a simple example based on the AngularJS tutorial. According to the Github project instructions (https://github.com/angular-ui/ui-select2), all I need is jQuery, Angular, and Ang ...

Obtain Parameters from .htaccess in AngularJS with the Help of UI-Router

My application is built using angular-translate for multi-language support and utilizes angularjs with ui-router. I'm currently facing an issue retrieving parameters from the redirect in the .htaccess file. I aim to establish the following routing st ...

Delete the last TD before adding the new element

Below is a snippet of jQuery code that I am working with: html += '<tr>'; html += '<td>AAA</td>'; html += '<td>BBB</td>'; html += '<td>CCC</td>'; html += '<td>DDD ...

The Boolean value retrieved from a NodeJS webservice behaves unexpectedly when incorporated into a test scenario

After calling a NodeJS webservice using the following code snippet: request({ url: "http://10.210.210.41:3001/trackable/lastPos", json: true }, function (error, response, body) { if (!error & ...

Modifying the CSS Property of a Non-React Element within a React Application

I am currently in the process of developing a React-based application that will operate within a Wordpress page. The application is mostly self-contained, but I am interested in being able to toggle the visibility of a div element on the page that is not p ...

Typescript's dynamic React component and its conditional types

I am currently working on a dynamic React component and I am facing an issue with properly passing the correct propType based on the selected component. The error arises when using <SelectComponent {...props.props} /> because the props do not match t ...

stop a element from being removed from the document

Is there a way to stop an element from being removed using something similar to preventDefault()? For example: myNode.on("remove", (e) => { e.preventDefault(); }); I have tried using MutationObserver to detect the removal, but so f ...

I am looking to retrieve the values of checked checkboxes in a MUI multi-select component

I am currently using Material-UI's mui multi select component and I need to determine whether an item is selected or unselected in order to set the correct state value. I have checked the event.target but it does not seem to have a checked attribute. ...

"What is the best way to execute this JavaScript function from the back-end of the

I am incorporating JavaScript generated controls (http://www.dariancabot.com/projects/jgauge_wip/) into my webpage. <div class="jgauge" ></div> $(document).ready(function () { var ctl; ctl = new jGauge(); ctl.init(); )} Sup ...

Showing the parents() function in HTML format on the navigation bar

My page is filled with button elements, and when a user hovers over one of them, I want to retrieve all of its ancestors and display them within the navbar either as HTML or an array. However, my current JavaScript code is not working as expected. Any su ...

The system couldn't locate 'concurrently' while attempting to access the Heroku logs

2017-10-08T20:06:11.093118+00:00 heroku[web.1]: Initiating process with command `npm start` 2017-10-08T20:06:15.431068+00:00 app[web.1]: 2017-10-08T20:06:15.431083+00:00 app[web.1]: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...