How to get remote image using jQuery asynchronously? - javascript

I want to show a remote image on my page. I use Bootstrap 2.3.2 Carousel. All the information comes from another web site's RSS feed. I get data into a div like the following:
...
<div id="newsItem-<?php echo $i;?>" class="item" data-src="<?php echo $feed[$i]->image; ?>" data-alt="<?php echo $feed[$i]->title; ?>">
</div>
...
The images takes too long to load. Page is loaded about 15 seconds. So I have decided to load images after the page loading finished.
There could be various dimensions of the pictures to be displayed.
I want to show the largest existing one.
For each news item, all the images may have different but similar dimensions such as 1024x768, 620x350, 528x350, 527x350.
I have written a jQuery script to achieve this but something is wrong.
jQuery(function () {
jQuery("div[id^='newsItem-']").each(function () {
var r = jQuery(this).attr("data-src");
var r620 = r.replace(".jpg", "-620x350.jpg");
var r527 = r.replace(".jpg", "-527x350.jpg");
var r1024 = r.replace(".jpg", "-1024x678.jpg");
var r528 = r.replace(".jpg", "-528x350.jpg");
var altImg = jQuery(this).attr("data-alt");
if (pictureExists(r1024)){
r = r1024;
}
else if (pictureExists(r620)){
r = r620;
}
else if (pictureExists(r528)){
r = r528;
}
else if (pictureExists(r527)){
r = r527;
}
jQuery(this).prepend("<img src='" + r + "' alt='" + altImg + "' />");
jQuery(this).removeAttr("data-alt");
jQuery(this).removeAttr("data-src");
});
});
function pictureExists(url) {
var img = new Image();
img.src = url;
if (img.height !== 0) {
return false;
} else {
return true;
}
}
I want to display the largest existing picture in the carousel.

You cannot know the height/width of the image until its loaded. So its an async process.
In pictureExists function try to do it in this way:
/ Create new image
var img = new Image();
// Create var for image source
var imageSrc = "http://example.com/blah.jpg";
// define what happens once the image is loaded.
img.onload = function() {
// Stuff to do after image load ( jQuery and all that )
// Within here you can make use of src=imageSrc,
// knowing that it's been loaded.
};
// Attach the source last.
// The onload function will now trigger once it's loaded.
img.src = imageSrc;
If you want to use the above way then you will have to implement promise structure to tackle the async nature of the image load to fetch the height/width
Or you can use this small plugin.
https://github.com/desandro/imagesloaded

Related

Preloading then adding additional images after page load to an image gallery on button click

I am building an image gallery that is populated from a JSON file. Everything works as intended currently, but as of right now there is no pre-loading of content after the initial page load. What I would like to happen is after the "view more" button is clicked I will have some "loading" text show, the batch of images will preload, the "loading" text will disappear, then the images will be added to the page once all items have loaded.
Here is the section of the code that involves the JSON fetch request and the building of elements on the page:
var HTML = '';
var itemsStart = 6; // Starting number of items on page.
var itemsAdd = 9; // Number of items to add to page at a time via button click.
var pItems = document.getElementById('pItems');
var pWrapper = document.getElementById('pItemWrapper');
function addProjects() {
pItems.insertAdjacentHTML('beforeend', HTML);
console.log('BUILD PROJECTS');
}
//Load json
fetch('data/projects.json').then(function (response) {
return response.json();
}).then(function (data){
//Loop through first set of items to load on page.
for (var i = 0; i < itemsStart; i++) {
HTML += '<img src="' + data.projects[i].Image + '" alt=""></img>';
if (i == (itemsStart - 1)) {
addProjects();
}
}
//Load additional items when clicking 'view more'.
document.getElementById('view-more').addEventListener('click', function() {
HTML = '';
for (var i = itemsStart; i < itemsStart + itemsAdd; i++) {
if ((i < data.projects.length)) {
HTML += '<img src="' + data.projects[i].Image + '" alt=""></img>';
}
if (i == ((itemsStart + itemsAdd) - 1) ) {
addProjects();
}
}
itemsStart = itemsStart + itemsAdd;
});
}).catch(function(error) {
console.error('Something went wrong');
});
I'm not using jQuery so I'd like to stick to vanilla js. I don't know what I need to add to my button event listener beyond what I have, I've never tried preloading images like this without using a plugin but I feel like I don't need to load an entire plugin just for this one thing and I'd like to understand how this would work.
EDIT
I feel like I'm almost there, but I still have something wrong. I made some modifications to have each item inside its own container, but instead of that happening I am creating an empty container for each pass of the loop, then the last container gets each image added to it. My code looks like this:
var itemsAdd = 3;
//Load additional items when clicking 'view more'.
document.getElementById('view-more').addEventListener('click', function() {
//The loop will add the next 3 items in the json file per click.
for (var i = itemsStart; i < itemsStart + itemsAdd; i++) {
var placeholder = document.createElement('div');
var src = 'img/portfolio/' + data.projects[i].url;
placeholder.innerHTML= '<div class="img-container">' + data.projects[i].Title + '</div>';
var galleryItem = placeholder.firstChild;
preloadImage(src).then(function (image) {
galleryItem.append(image);
});
pItems.append(galleryItem);
}
itemsStart = itemsStart + itemsAdd;
});
The result I get is this:
Is this because of how the promise works for the preloadImage function?
Generally you would create an image with JavaScript through either document.createElement('img') or the Image() constructor. Both result an in instance of an HTMLImageElement.
With this, you'll have an image that is not connected to the DOM, so it's not visible to you or the user. You can use this element to load the image behind the scenes by setting the image' src property.
Then by listening to the onload event you can determine whenever the image has finished loading. From here you could continue your flow by adding the image to the DOM and, for example, fade it in with animation.
The example below shows this process in the form of a function that returns a Promise. This promise will resolve whenever the load event has been triggered.
const preloadImage = src =>
new Promise(resolve => {
const image = new Image();
const onLoad = () => {
resolve(image);
};
image.addEventListener('load', onLoad, {once: true});
image.src = src;
});
Using it should be like this:
const src = 'http://example.com/my-image.jpg';
preloadImage(src).then(image => {
// Here the image has been loaded and is available to be appended, or otherwise.
document.body.append(image);
});
In your case you would loop over each image, call the function while passing the URL of the image, and append the image to the DOM when it's finished loading.
You can handle any animations, like fade-ins with CSS.
Real world implementation
So how should you implement this in your project? You'll need to start at the point where you create your images. Currently your images are created as strings. But strings are just strings, they aren't HTML elements, yet.
I'd recommend that you'll create a placeholder for each image. This placeholder could visually indicate that an image is loading and act as a wrapper for the image. Add this placeholder immediately to the pItems element.
Then load the image for each Image in your data.projects array by calling the preloadImage. Whenever the image is loaded, append it to the placeholder we've just created. You should now have the effect that first a placeholder is added and the images are starting to appear one by one.
The same logic should be applied for the load more loop.
...
}).then(function (data){
for (let i = 0; i < itemsStart; i++) {
// Create a <div class="placeholder"> which should act as a placeholder / wrapper.
const placeholder = document.createElement('div');
placeholder.classList.add('placeholder');
// Create the image based on the Image value.
// Whenever the image is loaded, add it to the placeholder.
const src = data.projects[i].Image;
preloadImage(src).then(image => {
placeholder.append(image);
});
// Immediately add the placeholder.
// This line doesn't wait for preloadImage to finish because preloadImage is asynchronous. Look into Promises if that is new to you.
pItems.append(placeholder);
}
...
});
From here you've got control over how the placeholder should look and any animations an image inside that placeholder should have.
I think you could put a <div> with black background over the loading image using css and when the image is ready remove it with js. You can detect when the image is loaded using the img.onload = () => {} function.
Or you could place there an img with the loading screen and replace it with the actual image when the image has loaded.

Connect function to pictures displayed from a PC folder

I'm pretty new to JS and programming altogether so I'm sorry in advance if the explanation is a little sloppy, but I'll try to make it as clear as possible.
So what I'm trying to do is have a JS code that reads and displays (in an HTML page) photos from a PC folder, makes them clickable and on the click it redirects you to a page with the same photo but in high resolution.
Now, I have this piece of code that displays the said pictures, but the thing is I don't seem to be able to figure out how to "connect" it to the pictures and make them clickable. What makes it more difficult is that I'm trying to make all of this code dynamic (as you can see I've done in the below code), so I would like not to have any hardcoded titles of pictures and so on.
var index = 1;
var tempImg = new Image();
tempImg.onload = function(){
appendImage();
}
var tryLoadImage = function(index){
tempImg.src = 'img/' + index + '.jpg';
}
var appendImage = function(){
var img = document.createElement('img');
img.src = tempImg.src;
document.body.appendChild(img)
tryLoadImage(index++);
}
tryLoadImage(index);
Any help is very much appreciated, thank you very much!
You can make your images clickable by adding an onclick function to them. Try something like this:
var appendImage = function(){
var img = document.createElement('img');
img.src = tempImg.src;
img.onclick = e => {
// do something you want to show the full picture like this maybe
var el = document.getElementById("fullpictureid");
if (el && e.target.src) {
el.src = e.target.src;
// so that it sets "src" in <img id="fullpictureid"> for example
}
};
document.body.appendChild(img)
tryLoadImage(index++);
}

How do I add loading indicator to an <img>?

I have the following HTML in my project.
<div class="container" id="crop">
<img id="timage" src="http://example.com/color/style/etc/" alt="timages" />
I also have the following javascript:
$(window).load(function () {
$("#slider").change(function update() {
sVal = $(this).val();
if (sVal == 2) {
$('#timage').prop('src',"http://example.com/" +
tForm +
"color.blahblah" +
itemCode +
"therest_ofthe_URL");}
sVal = $(this).val();
if (sVal == 3) {
$('#timage').prop('src',"http://example.com/" +
tForm +
"color.blahblah" +
itemCode +
"therest_ofthe_URL");}
);}
It works splendidly to replace the image with the string when the slider value reaches certain numbers. The problem is, the image is being created on the back end behind the scenes and takes quite some time before it is ready. In the meantime, you are just staring at the original image wondering if the slider did anything.
How do I add a loading indicator to let people know that the image is about to change?
First, place a loading indicator where you want it. You could replace #timage with a spinning gif, for example. Then use this code to start the new image loading:
var img = new Image();
img.onload = function () {
$('#timage').prop('src', img.src);
}
img.src = '/image/to/load/here';
The function will be executed when your new image has been retrieved from the server and loaded. Since it's already cached on the client, it should load instantly once the src for #timage is set.

javascript preloader/progress/percentage

I'm having trouble finding any good information on how to make a javascript(or jquery) progress bar WITH text that tells you the percentage.
I don't want a plug in, I just want to know how it works so that I can adapt it to what I need. How do you preload images and get a variable for the number of images that are preloaded. Also, how do you change html/css and-or call a function, based on the number of images that are loaded already?
<img> elements have an onload event that fires once the image has fully loaded. Therefore, in js you can keep track of the number of images that have loaded vs the number remaining using this event.
Images also have corresponding onerror and onabort events that fire when the image fails to load or the download have been aborted (by the user pressing the 'x' button). You also need to keep track of them along with the onload event to keep track of image loading properly.
Additional answer:
A simple example in pure js:
var img_to_load = [ '/img/1.jpg', '/img/2.jpg' ];
var loaded_images = 0;
for (var i=0; i<img_to_load.length; i++) {
var img = document.createElement('img');
img.src = img_to_load[i];
img.style.display = 'hidden'; // don't display preloaded images
img.onload = function () {
loaded_images ++;
if (loaded_images == img_to_load.length) {
alert('done loading images');
}
else {
alert((100*loaded_images/img_to_load.length) + '% loaded');
}
}
document.body.appendChild(img);
}
The example above doesn't handle onerror or onabort for clarity but real world code should take care of them as well.
What about using something below:
$('#btnUpload').click(function() {
var bar = document.getElementById('progBar'),
fallback = document.getElementById('downloadProgress'),
loaded = 0;
var load = function() {
loaded += 1;
bar.value = loaded;
/* The below will be visible if the progress tag is not supported */
$(fallback).empty().append("HTML5 progress tag not supported: ");
$('#progUpdate').empty().append(loaded + "% loaded");
if (loaded == 100) {
clearInterval(beginLoad);
$('#progUpdate').empty().append("Upload Complete");
console.log('Load was performed.');
}
};
var beginLoad = setInterval(function() {
load();
}, 50);
});
JSFIDDLE
You might also want to try HTML5 progress element:
<section>
<p>Progress: <progress id="p" max=100><span>0</span>%</progress></p>
<script>
var progressBar = document.getElementById('p');
function updateProgress(newValue) {
progressBar.value = newValue;
progressBar.getElementsByTagName('span')[0].textContent = newValue;
} </script>
</section>
http://www.html5tutorial.info/html5-progress.php

Javascript: Detect an image's loading status, and only swap out the old image when the new one is 'loaded'?

i call on a PHP script that generates graph images for me, however, it takes a few seconds. Is there a way to detect when it has finished loading, on the user side, and only swap it with the old image when the php script has finished and the image is ready?
here is the Javascript function i use to call the PHP script:
EDIT (CODE UPDATED)
function loadGraph(self,graph,varID) {
var img = new Image();
img.onload = function() {
$(self).parents().parents().siblings(".graph_container").empty().append(img);
};
img.src = 'drawGraph.php?type=journey_report&graph=' + graph +
(varID != null ? '&varID=' + varID : '') + '&companyID=<?php echo $_SESSION['companyID'] ?>';
}
and here is the graph container and the link that uses that function:
<div class="graph_container">
<img src="drawGraph.php?type=journey_report&graph=outOfDate_vs_upToDate&companyID=<?php
echo $_SESSION['companyID'] ?>" />
</div>
<div class="reportItemWrapper">
<div class="reportItem"><b>Total</b></div>
thanks!
Create an Image object and set its "onload" handler to a function that does what you do in that first block of code. Then set its "src" attribute to your URL.
var img = new Image();
img.onload = function() {
// that jQuery stuff
};
img.src = "drawGraph.php?type=journey_report ...";
Now that'll only work if the URL is cacheable. If not, then you could re-work that jQuery code so that you just stuff the Image element into the DOM.
$(self).parents().parents().siblings(".graph_container").empty().append(img);
(You'd still do that in the onload handler.)

Categories