Preloading images not working in Firefox? - javascript

I am preloading images like so:
$(function() {
window.onload = function() {
// Preloading colorized hover images
var bildliste_color = new Array();
var j;
for (j = 0; j < 14; j++) {
bildliste_color[j] = "images/works/work_art/middle/work_middle_art" + (j+1) + ".png";
}
var image_color = new Array();
for (j=0; j < bildliste_color.length; j++) {
image_color[j] = new Image();
image_color[j].src = bildliste_color[j];
}
// Preloading work_art_large_images
var bildliste_large = new Array();
var i;
for (i = 0; i < 14; i++) {
bildliste_large[i] = "images/works/work_art/large/work_large_art" + (i+1) + ".png";
console.log(i);
console.log(bildliste_large[i]);
}
var image_large = new Array();
for (i=0; i < bildliste_large.length; i++) {
image_large[i] = new Image();
image_large[i].src = bildliste_large[i];
}
}
});
I am preloading those images so that these are being cached and not being dowloaded again, when they are needed on hover.I achieved that with the jquery hover function like so:
$(document).ready(function() {
$("#incontent_work_art img").hover(function() {
oldsrc = $(this).attr("src");
var newsrc = $(this).attr("src").replace("images/works/work_art/middle/work_middle_art01sepia.png", "images/works/work_art/middle/work_middle_art1.png");
newsrc = newsrc.replace("images/works/work_art/middle/work_middle_art02sepia.png", "images/works/work_art/middle/work_middle_art2.png");
newsrc = newsrc.replace("images/works/work_art/middle/work_middle_art03sepia.png", "images/works/work_art/middle/work_middle_art3.png");
newsrc = newsrc.replace("images/works/work_art/middle/work_middle_art04sepia.png", "images/works/work_art/middle/work_middle_art4.png");
newsrc = newsrc.replace("images/works/work_art/middle/work_middle_art05sepia.png", "images/works/work_art/middle/work_middle_art5.png");
newsrc = newsrc.replace("images/works/work_art/middle/work_middle_art06sepia.png", "images/works/work_art/middle/work_middle_art6.png");
newsrc = newsrc.replace("images/works/work_art/middle/work_middle_art07sepia.png", "images/works/work_art/middle/work_middle_art7.png");
newsrc = newsrc.replace("images/works/work_art/middle/work_middle_art08sepia.png", "images/works/work_art/middle/work_middle_art8.png");
newsrc = newsrc.replace("images/works/work_art/middle/work_middle_art09sepia.png", "images/works/work_art/middle/work_middle_art9.png");
newsrc = newsrc.replace("images/works/work_art/middle/work_middle_art10sepia.png", "images/works/work_art/middle/work_middle_art10.png");
newsrc = newsrc.replace("images/works/work_art/middle/work_middle_art11sepia.png", "images/works/work_art/middle/work_middle_art11.png");
newsrc = newsrc.replace("images/works/work_art/middle/work_middle_art12sepia.png", "images/works/work_art/middle/work_middle_art12.png");
newsrc = newsrc.replace("images/works/work_art/middle/work_middle_art13sepia.png", "images/works/work_art/middle/work_middle_art13.png");
newsrc = newsrc.replace("images/works/work_art/middle/work_middle_art14sepia.png", "images/works/work_art/middle/work_middle_art14.png");
$(this).attr("src", newsrc);
}, function() {
$(this).attr("src", oldsrc);
});
});
This is for sure not the best code in the world but I am still learning. The current problem is that if I hover over an image it most of the time gets downloaded again by firefox. Even though I can see that all images were being downloaded by firefox previously. Sometimes the images are being loaded from the cache by firefox but it seems that after some amount of time the image is being downloaded again. I tested this also with opera und Chromium and it works well there. So why is Firefox downloading the image again and again and again? I want them to be cached!
I'd appreciate any good advice.
EDIT: It also works in IE. Could it possibly be that the problem is being caused because the preloaded images are not being added to the window.document.images array? In essence not in the DOM? My problem seems to be a bit if not fully related to this:
Image preloading isn't working for images in FireFox
But unfortunately no solutions were given.

Since you completely replace the old URLs by new ones, the garbage collector may decide to free memory because it doesn't know whether you'll use them again. You can't really assume how Firefox works (nor IE nor any other browser). Your best bet would be to have both sets of images in the web page at the same time and use the stylesheet display:none to select which set you don't want to show.

Related

Preloading Images in JavaScript (Need an Alert When Completed)

I have the following code below, which successfully preloads images into the browser cache when the PreloadAllImages function is called. Does anyone know how to send a simple alert, e.g. "All images have been preloaded into the browser cache." when the last image (or all images) is loaded. I have 300 images, so setTimeOut won't work for latency/download lag reasons. I've tried callbacks, placing alert commands in different places, etc... but have not been successful.
This code is based on JavaScript Only Method #1 found here. https://perishablepress.com/3-ways-preload-images-css-javascript-ajax/
function PreLoadAllImages() {
var images = new Array();
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image();
images[i].src = preload.arguments[i];
}
}
preload('Images/Image1.jpg', 'Images/Image2.jpg', ... , 'Images/Image300.jpg');
}
With some help, this is how the problem was solved in case anyone else needs it. Loaded images into an invisible div on the html page, then ran script to ensure everything was loaded. A button calls PreLoadAllImages() and then CheckImages().
var imagefiles = [
"Images/Image1.jpg",
"Images/Image2.jpg",
.....
"Images/Image300.jpg"];
function PreLoadAllImages () {
imagefiles.forEach(function(image){
var img = document.createElement('img');
img.src = image;
document.body.appendChild(img);});
$('img').hide();
}
var all_loaded;
function CheckImages() {
$('img').each(function(){ // selecting all image element on the page
var img = new Image($(this)); // creating image element
img.src = $(this).attr('src'); // pass src to image object
if(img.complete==false) {
all_loaded=false;
return false;
}
all_loaded=true;
return true;});
}
function CheckLoadingImages() {
var result;
var Checking=setInterval(function(){
result=CheckImages();
if(all_loaded==true) {
clearInterval(Checking);
MsgAfterLoading();
}
}, 2000);
}
function MsgAfterLoading() {
alert('All Images Loaded');
}
You could check if i is equals to the length of the array, so it will look like:
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
//the code
if (i == preload.arguments.length){
alert("Last image loaded");
}
//the code
}
Let me know if you have any questions.
Could you try looping through all the image elements and check the naturalWidth property, if they are all greater than 0 and its the last image then alert.
This link: Preloading Images in JavaScript (Need an Alert When Completed) should help
A promise might resolve your problem.
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise
var myPromise = new Promise( function(resolve, reject) {
// preload code
resolve(true);
};
myPromise.then(function() {
// your alert
};
You can use the onload event.
function PreLoadAllImages() {
var images = new Array();
var numberofimages = 0, loadedimages = 0;
function preload() {
numberofimages = preload.arguments.length;
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image();
images[i].src = preload.arguments[i];
images[i].onload = () => {
loadedimages++;
if(loadedimages == numberofimages){
alert("All images are loaded");
}
}
}
}
preload('Images/Image1.jpg', 'Images/Image2.jpg', ... , 'Images/Image300.jpg');
}

Random image appear when website is loaded

I have 2 pictures for my website, and i want it to load one of them whem the website loads.
I have tried using some javascript. But i am quite new to all this.
This is how i am think i want to make it.
<div class="image">
Show one of 2 images here.
</div>
<script>
var r = Math.floor(Math.random() * 100) + 1;
if(r < 51) {
SHOW IMAGE 1
}
else {
SHOWIMAGE 2
}
</sccript>
So i was hoping someone could teach me how to actually turn this into functional code.
Thanks.
You can set the src attribute of an image directly using javascript, then use Math.random like you expected to pick between different image urls.
With an image tag with id 'random_image':
// images from wikipedia featured images/articles 2015-03-03
var img = document.getElementById('random_image');
if (Math.random() > .5) {
img.src = 'http://upload.wikimedia.org/wikipedia/en/thumb/4/45/Bradford1911.jpg/266px-Bradford1911.jpg';
} else {
img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/Pitta_sordida_-_Sri_Phang_Nga.jpg/720px-Pitta_sordida_-_Sri_Phang_Nga.jpg';
}
Here is a jsfiddle example: http://jsfiddle.net/8zd5509u/
1.way:
var _img = document.getElementById('id1');
var newImg = new Image;
newImg.onload = function() {
_img.src = this.src;
}
newImg.src = 'http://www.something.blabla.....';
another:
function preload(images) {
if (document.images) {
var i = 0;
var imageArray = new Array();
imageArray = images.split(',');
var imageObj = new Image();
for(i=0; i<=imageArray.length-1; i++) {
//document.write('<img src="' + imageArray[i] + '" />');// Write to page (uncomment to check images)
imageObj.src=imageArray[i];
}
}
}
Then in the of each web page, add the following code after you've called the main JavaScript file:
<script type="text/javascript">
preload('image1.jpg,image2.jpg,image3.jpg');
</script>

Use javascript to write html around loop

I'm using the javascript from this older script: JavaScript: how to load all images in a folder?
However, I want to use the same javascript file to write some html code before the loop and some after the loop, all using this same javascript file.
Just putting a document.write before and after it in the javascript doesn't work.
var bCheckEnabled = true;
var bFinishCheck = false;
var img;
var imgArray = new Array();
var i = 0;
var myInterval = setInterval(loadImage, 1);
function loadImage() {
if (bFinishCheck) {
clearInterval(myInterval);
document.write('Loaded ' + i + ' image(s)');
return;
}
if (bCheckEnabled) {
bCheckEnabled = false;
img = new Image();
img.onload = fExists;
img.onerror = fDoesntExist;
img.src = 'assets/' + i + '.png';
document.write('<img src="assets/' + i + '.png" width="1016" height="813" alt="Kar" />');
}
}
function fExists() {
imgArray.push(img);
i++;
bCheckEnabled = true;
}
function fDoesntExist() {
bFinishCheck = true;
}
You may be using this example code incorrectly. Its intent appears to be to pre-load the image files in the background, not display them to the user in the HTML (yet). This is to improve apparent download speed of your page.
In short, this code doesn't actually render the image into the DOM; and that is intentional behavior.

jQuery/javascript - Get Image size before load

I have a list of images that is rendered as thumbnails after upload. The issue that I have is I need the dimensions of the fully uploaded images, so that I can run a resize function if sized incorrectly.
Function that builds the image list
function buildEditList(json, galleryID)
{
//Hide the list
$sortable = $('#sortable');
$sortable.hide();
for(i = 0, j = json.revision_images.length; i < j; i++) {
$sortable.append(
"<li id='image_" + json.revision_images[i].id + "'><a class=\"ui-lightbox\" href=\"../data/gallery/"
+ galleryID
+ "/images/album/"
+ json.revision_images[i].OrgImageName
+ "\"><img id=\""
+ json.revision_images[i].id
+ "\" alt=\"\" src=\"../data/gallery/"
+ galleryID
+ "/images/album/"
+ json.revision_images[i].OrgImageName
+ "\"/></a></li>"
).hide();
}
//Set first and last li to 50% so that it fits the format
$('#sortable li img').first().css('width','50%');
$('#sortable li img').last().css('width', '50%');
//Fade images back in
$sortable.fadeIn("fast",function(){
var img = $("#703504"); // Get my img elem -- hard coded at the moment
var pic_real_width, pic_real_height;
$("<img/>") // Make in memory copy of image to avoid css issues
.attr("src", $(img).attr("src"))
.load(function() {
pic_real_width = this.width; // Note: $(this).width() will not
pic_real_height = this.height; // work for in memory images.
});
alert(pic_real_height);
});
}
I have been trying to use the solution from this stackoverflow post, but have yet to get it to work, or it may just be my code. if you have any ideas on this I could use the help. Currently the alert is coming back undefined.
There's a newer js method called naturalHeight or naturalWidth that will return the information you're looking for. Unfortunately it wont work in older IE versions. Here's a function I created a few months back that may work for you. I added a bit of your code below it for an example:
function getNatural($mainImage) {
var mainImage = $mainImage[0],
d = {};
if (mainImage.naturalWidth === undefined) {
var i = new Image();
i.src = mainImage.src;
d.oWidth = i.width;
d.oHeight = i.height;
} else {
d.oWidth = mainImage.naturalWidth;
d.oHeight = mainImage.naturalHeight;
}
return d;
}
var img = $("#703504");
var naturalDimension = getNatural(img);
alert(naturalDimension.oWidth, naturalDimension.oHeight)​

Generic Javascript Image Swap

I'm building a navigation bar where the images should be swapped out on mouseover; normally I use CSS for this but this time I'm trying to figure out javascript. This is what I have right now:
HTML:
<li class="bio"><img src="images/nav/bio.jpg" name="bio" /></li>
Javascript:
if (document.images) {
var bio_up = new Image();
bio_up.src = "images/nav/bio.jpg";
var bio_over = new Image();
bio_over.src = "images/nav/bio-ov.jpg";
}
function over_bio() {
if (document.images) {
document["bio"].src = bio_over.src
}
}
function up_bio() {
if (document.images) {
document["bio"].src = bio_up.src
}
}
However, all of the images have names of the form "xyz.jpg" and "xyz-ov.jpg", so I would prefer to just have a generic function that works for every image in the navbar, rather than a separate function for each image.
A quick-fire solution which should be robust enough provided all your images are of the same type:
$("li.bio a").hover(function() {
var $img = $(this).find("img");
$img[0].src = $img[0].src.replace(".jpg", "") + "-ov.jpg";
}, function() {
var $img = $(this).find("img");
$img[0].src = $img[0].src.replace("-ov.jpg", "") + ".jpg";
});
This should work will all image formats as long as the extension is between 2 and 4 characters long IE. png, jpeg, jpg, gif etc.
var images = document.getElementById('navbar').getElementsByTagName('img'), i;
for(i = 0; i < images.length; i++){
images[i].onmouseover = function(){
this.src = this.src.replace(/^(.*)(\.\w{2,4})$/, '$1'+'-ov'+'$2');
}
images[i].onmouseout = function(){
this.src = this.src.replace(/^(.*)-ov(\.\w{2,4})$/, '$1'+'$2');
}
}
Here's an idea in plain javascript (no jQuery):
function onMouseOverSwap(e) {
e.src = e.src.replace(/\.jpg$/", "-ov.jpg"); // add -ov onto end
}
function onMouseOutSwap(e) {
e.src = e.src.replace(/(-ov)+\.jpg$/, ".jpg"); // remove -ov
}

Categories

Resources