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

Update: The sum of products and total cost are correctly calculated, however, the values are not being updated when the quantity is adjusted

I understand how to calculate the sum of products and total cost, but I want the values to update automatically when item quantities change. .filter('total', function () { return function (input, property) { var i = input instanceof ...

There was a type error that occurred because the property 'addEventListener' could not be read from an undefined value

Encountering an issue with the JavaScript libraries three.js and OrbitControls.js despite following a tutorial: However, an error is being displayed in the console: Uncaught TypeError: Cannot read property 'addEventListener' of undefined at ne ...

While troubleshooting the app, I encountered an error that says: "The property 'answers' cannot be read as it is undefined."

Everything was going smoothly with my app until it suddenly crashed, displaying the error message "Cannot read property 'answers' of undefined". Let's take a look at the specific piece of code causing the issue: function mapStateToProps({ ...

The "begin" parameter of the Angular limitTo filter appears to be ineffective in Angular version 1.3

Currently, I am attempting to implement a pagination feature on an array of users using Angularjs 1.3. ng-repeat="user in users | filter: searchText | orderBy: 'lastName' | limitTo:pageSize:startPosition track by user.lanId" I specifically want ...

Add fresh inline designs to a React high-order component creation

Applying a common HOC pattern like this can be quite effective. However, there are instances where you may not want a component to be wrapped, but rather just extended. This is the challenge I am facing here. Wrapper HOC const flexboxContainerStyles = { ...

The problem stemming from the implementation of the useNavigate() Hook in a personalized React-Admin application

I've encountered a complex issue in my React-Admin application. Whenever I attempt to utilize the useNavigate() hook within my custom login component (MyLoginPage), an error message pops up: [Route] is not a <Route> component. All component chi ...

failure of pipe during search for art gallery information

Hi, I've created a filter pipe to search for imagenames and imageids among all my images. However, it seems to only find matches in the first image. There seems to be something wrong with my code. This is my FilterPipe class in filter.pipe.ts where I ...

Steps to create a pop-up displaying a unique message ID retrieved from my database

My goal is to implement a pop-up message dialog on my website. When a user clicks on a reply icon, a pop-up message will appear with a textarea for the user to respond to a question they have been asked. The current issue is that clicking on the tag alway ...

Having trouble implementing express-unless to exclude specific routes from requiring authentication

Being relatively new to JavaScript and Node.js, I decided to incorporate express-jwt for authenticating most of my APIs. However, I wanted to exclude certain routes like /login and /register from authentication. After exploring the documentation for expr ...

Error encountered in Listings#index with ExecJS RuntimeError

Upon launching my localhost, I encountered an ExecJS error message that has left me puzzled. Any assistance would be greatly appreciated. A Glimpse into My Localhost The issue originates from /.../conektec/app/views/layouts/application.html.erb, specific ...

In the world of Vue3 and Vue-Router, accessing parameters using the $route object is a breeze during development, but may prove trick

Struggling with building a Vue3 app for production as 90% of my scripts are broken due to variables being undefined. It's baffling why this happens. One concrete example is: In dev mode, accessing a parameter value in my route using this.$route.param ...

Having trouble with router.push in Vue3 and Vuex4?

Encountering some issues with Vue 3 and Vuex. Attempting to redirect users when logged in within my Vuex file, but the redirection is not happening as expected. No errors are being returned, only a link change without actually redirecting to another page. ...

Creating Vue.js components dynamically

Is it possible to programmatically insert a modal component in Vue? For instance: Vue.component('modal', {...}) Then, in any component, is there a way to do something like this: Vue.component('login', { methods: { openLoginM ...

Variations in Angular scope variable behavior

Code Snippet in HTML <input ng-model="test1.param"> <input ng-model="test2"> Code Snippet in Controller $scope.test1 = { param: null }; $scope.test2 = null; Upon entering text in both input fields: The value of $scope.test1.param changes ...

Enhance the functionality of jqGrid by customizing key bindings for arrow and tab keys

In order to enhance my jqGrid functionality, I am seeking to implement the ability for users to press different keys for specific actions. For example, pressing Enter should save data (which is currently working fine), while pressing the left arrow key sho ...

What does the "done" callback function entail in Node.js?

Many npm packages commonly utilize a "done" callback function in their code. I find it challenging to grasp its purpose. For instance: passport.serializeUser(function(user, done) { done(null, user.id); }); From what I can gather: The "done" function a ...

`Need help setting the active class for a bootstrap navbar using Angular JS?`

In my bootstrap navbar, I have the following menu items: Home | About | Contact I'm looking to assign the active class to each menu item based on the current angular route. Specifically, how can I set class="active" when the angular route is at # ...

Tips for incorporating several d3 elements on a single webpage

I am currently facing an issue where I am attempting to add a line graph below a d3 map, but the map and line graph are appearing below where the map should be located. I have tried creating separate div tags with distinct id's, but I am unsure of wha ...

Using both withNextIntl and withPlaiceholder simultaneously in a NextJS project causes compatibility issues

I recently upgraded to NextJS 14 and encountered an issue when deploying my project on Vercel. The next.config.mjs file in which I wrapped my nextConfig in two plugins seemed to prevent the build from completing successfully. As a workaround, I decided t ...

Animating the opacity of elements using jQuery and CSS

Trying to put together a fading slideshow with five slides that will loop back to the beginning. My code seems like it should do the trick, but there's something not quite right. <script type="text/javascript"> $(document).ready(function( ...