image source that changes dynamically with a placeholder image

Currently, I am facing a certain issue. Unfortunately, I cannot provide a plunkr example as the image is sourced from a protected site and there are no open URLs available that constantly serve changing images. Additionally, I am unable to use a local animated image because it must be hosted on an external server in order to demonstrate the problem. Despite this limitation, the concept is quite simple.

The URL I am utilizing to display an image is being sent from a server that changes the image at a rate of approximately 3 frames per second.

<img ng-src="{{LoginData.url}}/cgi-bin/nph-zms?mode=jpeg&amp;monitor={{monitorId}}&maxfps=3&buffer=1000&user={{LoginData.username}}&pass{{LoginData.password}}&rand={{rand}}" width="100%" style="backgroundimage:url('http://placeholder.com/placeholder.jpg');"/>

Here lies the issue: I would like to display a placeholder text or image in the following scenarios: a) The server may take some time to render the initial frame. b) Sometimes, the server fails to send any images at all

I want to prevent the screen from remaining blank in order to avoid causing confusion for the user.

The main problem I am encountering is that when the img-src loads, the screen turns white briefly before the actual images start streaming (scenario a) or remains blank for an extended period (scenario b).

I have tried different methods such as using a background image as shown in the code above. However, this only appears if there is an error in loading the img-src. In my case, it momentarily displays but then turns white once the img-src is encountered (until the server sends the images).

In addition, I have explored various techniques including the app.directive global image trap method mentioned in if a ngSrc path resolves to a 404, is there a way to fallback to a default?

The main challenge here is that my situation does not involve an image error. It seems like the server experiences delays without returning an HTTP error, causing the image window to turn white during that timeframe. I am looking to address this by overlaying text (or an image) on top of it until the actual images begin to arrive.

Thank you

Answer №1

Recently, I created a custom directive to show a placeholder image in case there is an error with the server:

.directive('placeholderImg', function() {
    //default place holder
    return {
        restrict: 'A',
        link: function(scope, element, attr) {
            var img = window.scriptRoot + 'img/divers/avatar_min.jpg';
            if (attr.placeholderImg) {
                switch (attr.placeholderImg) {
                    case 'profile':
                        img = 'img/avatar.png';
                        break;
                    case 'profile_small':
                        img = 'img/avatar_min.png';
                        break;
                    case 'profile_large':
                        img = '/img/nothumb.png';
                        break;
                    //Add more placeholders
                } 
            }

            //If ngSrc is empty
            if (!attr.ngSrc)
                element[0].src = img;

            //If there is an error (404)
            element.on('error', function() {
                element[0].src = img;
            });

        }
    };
});

This directive can be implemented like this:

<img data-ng-src="{{app.picture}}" data-placeholder-img="profile_large">

If your concern is about showing something while the image is loading, you can modify the directive by setting element[0].src to a placeholder initially and then updating it once the image loads, similar to how the error event is handled.

Answer №2

Instead of relying heavily on JS for logic, I suggest utilizing background images in CSS. We can incorporate a small icon on a grey background as a placeholder, and when the image URL loads, leverage z-index to display the image over the color and icon. For more details, check out my post here.

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

Issue with Date Picker not properly storing selected date in MySQL database

My goal is to save the datepicker date to MySQL by selecting the date format using JavaScript. I have verified that the date format appears correct as YYYY-MM-DD when logging to the console. However, when I try to execute an INSERT query to MySQL, the date ...

Combining Multiple Arrays into a Single Array

Is there a way to combine this merge operation that creates one array using forEach into a single array at the end? affProd.pipe(mergeMap( event1 => { return fireProd.pipe( map(event2 => { const fi ...

Is there a built-in function in Firefox that can retrieve a list of all indexedDB names stored in the

When working in chrome, I utilized the window.indexedDB.databases() method to retrieve all indexedDb names. However, this same method does not seem to be functioning in firefox. In an attempt to resolve this issue, I will explore alternative methods such ...

A guide to finding the mean in Angular by utilizing JSON information

import { Component, OnInit } from "@angular/core"; import { MarkService } from "../app/services/marks.service"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.scss"] }) export class AppComp ...

Storing data using angular-file-upload

In my application, I am utilizing the "angular-file-upload" library to save a file. Here is the code snippet that I am using: $scope.submitForm = function(valid, commit, file) { file.upload = Upload.upload({ url: '/tmp', data ...

Utilizing Loops to Generate Unique CSS Designs on an HTML Page

View reference image ->Take a look at the reference image provided. ->In the image, a for loop is used to create box designs and displayed above. ->The goal is to change the background color and border color of all boxes using a single HTML cla ...

Using the Angular translate filter within a ternary operator

I am currently working on translating my project into a different language. To do this, I have implemented the Angular Translate library and uploaded an external JSON file containing all the translations. Here is an example of how it looks: { "hello_wor ...

What is the best way to set a value for a variable within a UI component in React?

I'm still learning the ropes with React and JavaScript. My current challenge involves declaring a temporary variable and assigning the value of companyData.name to it, as I need to gather data from two variables like companyData.name. Below is my cod ...

What is the duration that browsers retain downloaded assets during a single session?

Is it necessary to preload data from the server in order to have immediate access when needed? The data is stored in a file named "data.json". Initially, I considered storing data.json in an object and referencing it whenever required. However, given tha ...

Tips for navigating upwards to a specific element and successfully clicking on it in Selenium

I am facing a situation where the system needs to scroll upwards to reach the web element located in the left panel of the page and then click on it to proceed with other operations. I have attempted various methods but none seem to be effective. Can anyon ...

Creating a simple Node.js project using material web components - a step-by-step guide

I have recently started experimenting with Node.js. This is a basic program I created to test the integration of material-components-web. I followed the instructions provided in the readme file and here's what I have implemented so far: package.json ...

Display a DIV next to the mouse cursor when a span is hovered over

Is there a way to make a DIV element appear at the mouse cursor when a user hovers over a SPAN or another DIV? I attempted to create a function for this purpose, but unfortunately, it does not seem to be working properly even though jQuery is correctly lo ...

Sorting the keys of objects within an array

Currently, I am in the midst of an evaluation where I have the freedom to utilize any resources at my disposal. The task at hand involves using the .filter method to remove objects without a specific key. Here is the provided prompt... Create a function n ...

You cannot assign an optional parameter in Express after it has already been declared

Having trouble with passing optional parameters in my param function as defined below. During testing in Postman, I keep encountering a Reference Error 'off' is not defined. It seems like I'm missing something crucial in how to utilize the p ...

Having trouble with ReactJS updating the state in the correct format using moment?

In my ReactJS project, I am using a datepicker feature. However, I have encountered an issue where the state is not being updated with the selected date value after formatting it using moment.js. const [selectedDates, setSelectedDates] = useState([]) ...

Uniting 2 streams to create a single observable

I am in the process of merging 2 different Observables. The first Observable contains a ShoppingCart class, while the second one holds a list of ShoppingItems. My goal is to map the Observable with shopping cart items (Observable<ShoppingItems) to the i ...

Can I extract JSON data from the AJAX response?

When receiving JSON data, such as in the example below, it is often necessary to separate each value into individual variables: var reviewDate ='2015-06-01T05:00:00Z' var developers ='Ankur Shah,Srikanth Vadlakonda,Tony Liu, Qiuming Jie&ap ...

An issue encountered while implementing a post method with fetch and Express

I'm just starting out, so I hope my question isn't too basic. My goal is to send a longitude and latitude from client-side JavaScript to a Node.js server using Fetch and Express.js. Below is the HTML code snippet: <!DOCTYPE html> <html ...

Use ng-repeat to extract information from an array and populate it into a datalist

I've already tried searching for a solution to my issue on Google, but I couldn't find anything that really helped me. I'm looking to create an input field that also functions like a dropdown. This way, I can either type in my own data or se ...

Activate the button when the password is correct

Check out my code snippet: $("#reg_confirm_pass").blur(function(){ var user_pass= $("#reg_pass").val(); var user_pass2=$("#reg_confirm_pass").val(); var enter = $("#enter").val(); if(user_pass.length == 0){ alert("please fill password ...