Display a Loading icon while images loads - javascript

I want to show a background image/loading spinner inside a div that will load an image inside of it, the image will show once it's fully loaded doing something like this:
<div style="background-image:url('imageThatWillAppearBeforeLoad')"></div>
Demo (In jQuery)
How can I have the same using Angular2/Ionic2?

Create a component that shows the placeholder image until the requested image is loaded, and hides the requested image. Once the image is loaded, you hide the placeholder and show the image.
#Component({
selector: 'image-loader',
template: `<img *ngIf="!loaded" src="url-to-your-placeholder"/>
<img [hidden]="!loaded" (load)="loaded = true" [src]="src"/>`
})
export class ImageLoader {
#Input() src;
}
See it working in Plunker.
Update
Now that I understand the requirements better, here's a solution with background image. It's a little hacky, and I like the original one better...
#Directive({
selector: '[imageLoader]'
})
export class ImageLoader {
#Input() imageLoader;
constructor(private el:ElementRef) {
this.el = el.nativeElement;
this.el.style.backgroundImage = "url(http://smallenvelop.com/demo/image-loading/spinner.gif)";
}
ngOnInit() {
let image = new Image();
image.addEventListener('load', () => {
this.el.style.backgroundImage = `url(${this.imageLoader})`;
});
image.src = this.imageLoader;
}
}
Updated plunker.

Here is a copy of one of my posts
I finally solved that problem with CSS! When an image is loading in ionic 2, the ion-img tag doesn't have any class. However, when the image is finally loaded, the ion-img tag get the class "img-loaded".
Here is my solution :
<ion-img [src]="img.src"></ion-img>
<ion-spinner></ion-spinner>
And my CSS :
.img-loaded + ion-spinner {
display:none;
}

Simply use this function
loadImage(element: HTMLElement, imagePath: string, spinnerPath: string) {
element.tagName === 'img'
? element.setAttribute('src', spinnerPath)
: (element.style.background = `url(${spinnerPath}) 50% 50% no-repeat`);
const image = new Image();
image.crossOrigin = 'Anonymous';
image.src = imagePath;
image.onload = () => {
element.tagName === 'img'
? element.setAttribute('src', imagePath)
: (element.style.background = `url(${imagePath})`);
};
}
You don't have to worry about your element is image or div or whatever it is?
example if you didn't figure out how to use it
ngOnInit() {
const myElement = document.getElementsByClassName('my-element')[0];
// or however you want to select it.
const imagePath = 'path/to/image.png';
const spinnerPath = 'path/to/spinner.gif'; // or base64 spinner url.
this.loadImage(myElement, imagePath, spinnerPath);
}
Happy coding 😉

Related

JQuery append image not showing

For this code block
$(document).ready(() => {
for (let i = 0; i < 10; i++) {
$("#main").append(factory());
}
});
this will show the image:
function factory() {
return $('<image class="champ-icon rounded-circle" src="resources/irelia.jpg" />');
}
while this doesn't
function factory() {
let $champIcon = $(document.createElement("image"))
.addClass("champ-icon rounded-circle")
.attr("src", "resources/irelia.jpg");
return $champIcon;
}
I'm using Bootstrap 4 as well.
The page currently is just a static mock up. I want to dynamically build elements from data given to it by a local server.
I literally just messed around with HTML/CSS and jQuery over the weekend so I'm not sure what went wrong here. Shouldn't both function return the same jQuery object?
Thanks!
CSS class
.champ-icon {
width: 100px;
height: 100px;
}
Edit: creating it with normal javascript works as well.
function factory() {
let img = new Image();
img.src = "resources/irelia.jpg";
img.className = "champ-icon rounded-circle";
return img;
That's because you are trying to programmatically create <image> element in html, which... doesn't exist. To insert element on a page you should use <img src="">, not <image...>. Change this line
let $champIcon = $(document.createElement("image"))
to
let $champIcon = $(document.createElement("img"))
And it should work.

Prerender images from URL in reactjs

Is it possible to prerender a list of images based on URL to prevent first loading on display with react or JS?
Thanks in advance.
EDIT: I have a carousel of images and all images are display one by one. When an image are are display for the first time this image take some time to be render because she need to be get from the url. And if I display this same image a second time I will not wait. Then I want to know if there is a solution to preload all images directly after get the url in a ComponentDidMount even the loading become longer.
An other example: I have a list of image and I want display them all at the same time. How can I preload them all before end the loading and start the render.
Do you simply want to preload images in advance?
The article of the Preloading Content might help.
componentDidMount() {
const imageUrlList = ['a.jpg', 'b.jpg', 'c.jpg'];
this.preloadImages(imageUrlList);
}
preloadImages(urlList) {
let fragment = document.createDocumentFragment();
for (let i = 0; i < urlList.length; i++) {
const imgUrl = urlList[i];
const linkEl = document.createElement('link');
linkEl.setAttribute('rel', 'preload');
linkEl.setAttribute('href', imgUrl);
linkEl.setAttribute('as', 'image');
fragment.appendChild(linkEl);
}
document.head.appendChild(fragment);
}
Not so clear from what you mean by prerender.
By preloading, do you mean that you want that the component renders only when the image is ready?
If so, you could do something like this:
componentDidMount() {
const img = new Image();
img.src = Newman; // by setting an src, you trigger browser download
img.onload = () => {
// when it finishes loading, update the component state
this.setState({ imageIsReady: true });
}
}
render() {
const { imageIsReady } = this.state;
if (!imageIsReady) {
return <div>Loading image...</div>; // or just return null if you want nothing to be rendered.
} else {
return <img src={Newman} /> // along with your error message here
}
}

How to get ALT from IMG tag in JavaScript

I am using THIS script to display my galleries in lightbox. I was using some plugins but all of them does not display the alt=""(alt added in media in wordpress).
How can I modify the code from the link below to display the alt attributes ?
I found something in the code, but I dont know how to put the dynamic alt there(commented by uppercase text in the code). Dynamic I mean that as user will add the img in wordpress dashboard, he will put the alt then.
{
key: '_preloadImage',
value: function _preloadImage(src, $containerForImage) {
var _this4 = this;
$containerForImage = $containerForImage || false;
var img = new Image();
if ($containerForImage) {
(function () {
// if loading takes > 200ms show a loader
var loadingTimeout = setTimeout(function () {
$containerForImage.append(_this4._config.loadingMessage);
}, 200);
img.onload = function () {
if (loadingTimeout) clearTimeout(loadingTimeout);
loadingTimeout = null;
var image = $('<img />');
image.attr('src', img.src);
image.addClass('img-fluid');
image.attr('alt',"Temp TEXT"); // HERE I WOULD LIKE TO DISPLAY THE ALT AUTOMATICALLY - NOT STATIC AS IT IS NOW
// backward compatibility for bootstrap v3
image.css('width', '100%');
$containerForImage.html(image);
if (_this4._$modalArrows) _this4._$modalArrows.css('display', ''); // remove display to default to css property
_this4._resize(img.width, img.height);
_this4._toggleLoading(false);
return _this4._config.onContentLoaded.call(_this4);
};
img.onerror = function () {
_this4._toggleLoading(false);
return _this4._error(_this4._config.strings.fail + (' ' + src));
};
})();
}
img.src = src;
return img;
}
},
I am using wordpress on my page and my skills in JS are rather poor, so I am asking you :).
We don't really know what is the type of your img variable. If you want to set the alt tag of image to the one of img, simply do:
image.attr('alt', img.attr('alt'));
…if it's a jQuery object. Otherwise, if img is pure JavaScript, you can do:
image.attr('alt', img.alt);
if the img object holds the existing alt and image is the new jQuery object, then set it with jQuery
image.attr('alt', img.getAttribute('alt'))

object HTMLImageElement showing instead of image

I created an array of 2 images and tried to display them, but instead of the images I got the text:
object HTMLImageElement
I am sure my images are in the right directory which I am currently working with.
< template is="auto-binding">
<section flex horizontal wrap layout>
<template repeat="{{item in items}}">
<my-panel>{{item}}</my-panel>
</template>
</section>
<script>
(function() {
addEventListener('polymer-ready', function() {
var createImage = function(src, title) {
var img = new Image();
img.src = src;
img.alt = title;
img.title = title;
return img;
};
var items = [];
items.push(createImage("images/photos/1.jpeg", "title1"));
items.push(createImage("images/photos/2.jpeg", "title2"));
CoreStyle.g.items = items;
addEventListener('template-bound', function(e) {
e.target.g = CoreStyle.g;
e.target.items = items;
});
});
})();
</script>
What am I missing here?
Use:
items.push(createImage(...).outerHTML);
Edit: Changes to original question has rendered the rest of the answer obsolete. But I am leaving it anyway in the hope that OP or someone may learn something.
I got the text: object HTMLImageElement
I am pretty sure you are using something like this to add the new element to DOM:
document.getElementById('#insert_image_here').innerHTML = items[0];
(Edit: What happens here is this: your newly created object items[0] is an HTMLImageElement. When you try to assign it to innerHTML, since innerHTML is type of String, JavaScript will try to call the objects toString() method and set the returned value to innerHTML. For DOM elements toString always returns object XElement.)
What you need to do is this:
document.getElementById('#insert_image_here').appendChild(items[0]);
The easiest and safest way to do this is to put the img in the template and bind the src and title attributes like this:
<template repeat="{{item in items}}">
<my-panel><img src="{{item.src}}" alt="{{item.title}}" title="{{item.title}}"></my-panel>
</template>
Then createImage looks like this
var createImage = function(src, title) {
return {src: src, title: title};
}
Replace
var createImage = function(src, title) {
var img = new Image();
img.src = src;
img.alt = title;
img.title = title;
return img;
};
With
var createImage = function(src,title) {
title = title.replace(/"/g,""");
return '<img src="'+src+'" title="'+title+'" alt="'+title+'" />';
}
It looks like whatever framework thingy you're using is expecting strings, not Image objects ;)

Display image through html image element object

I have the following code :
function createImage(source) {
var pastedImage = new Image();
pastedImage.onload = function() {
}
pastedImage.src = source;
}
The function createImage contain the source parameter which contain the source of an image. After that I created the object pastedImage of class Image and after alerting that I am getting the html image element object like [object HTMLImageElement].
My question is how I can display image into my html page using that object. I want to display it after onload function.
Hiya : Working demo http://jsfiddle.net/wXV3u/
Api used = .html http://api.jquery.com/html/
In demo click on the click me button.
Hope this helps! Please lemme know if I missed anything! B-)
Code
$('#foo').click(function() {
createImage("http://images.wikia.com/maditsmadfunny/images/5/54/Hulk-from-the-movie.jpg");
});
function createImage(source) {
var pastedImage = new Image();
pastedImage.onload = function() {
}
pastedImage.src = source;
$(".testimonialhulk").html(pastedImage);
}​
Also you can do like this :
function createImage(source) {
var pastedImage = new Image();
pastedImage.onload = function() {
document.write('<br><br><br>Your image in canvas: <img src="'+pastedImage.src+'" height="100" width="200"/>');
}
pastedImage.src = source;
}​
Simple, and better, using javascript dom primitive (replaceChild):
Get the parent of the image, the div or span that contains it, and replace the old img tag with the new image object you created with your function
var domImgObj = document.getElementById("image");
var imgObj = createImage(src); // your function
imgObj.id = pageimgObj.id; // necessary for future swap-outs
document.getElementById("container").replaceChild(imgObj,domImgObj);
document.createRange().createContextualFragment(img.outerHTML)
Example
const img = new Image()
img.src = "https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico"
const frag = document.createRange().createContextualFragment(`${img.outerHTML}`)
document.querySelector(`body`).append(frag)

Categories

Resources