Preloading images with js - javascript

I used this tutorial to make image slider at my site. But I have more than 100 images. It will be hard to load everything when page loads. So, any tricks to preload first ~10 images, and when I'll slide to the 9th, for example, load another 10?
Or there is already-prepared plugin for jquery which provides this?

with jquery, something as simple as this works:
$('<img />')[0].src = 'image.jpg';
it creates an element but never adds it to the page
so the image is loaded, but never shown
check the Net panel in firebug to see it loaded.

With jQuery I use this:
(function($) {
var cache = [];
$.preLoadImages = function() {
var args_len = arguments.length;
for (var i = args_len; i--;) {
var cacheImage = document.createElement('img');
cacheImage.src = arguments[i];
cache.push(cacheImage);
}
}
})(jQuery)
jQuery.preLoadImages("/images/img01.jpg","/images/img02.jpg");

Related

JavaScript Image Preload in function

first of all I don't really know anything about JavaScript.
I have a website slideshow with the following code:
//* Slideshow 1 *//
var slider_img_1 = document.querySelector(".image_slide_1");
var images_1 = ["fabric1_1.jpg", "fabric1_2.jpg", "fabric1_3.jpg", "fabric1_4.jpg", "fabric1_5.jpg"];
var i = 0;
//* Slideshow 2 *//
var slider_img_2 = document.querySelector(".image_slide_2");
var images_2 = ["book1_1.jpg", "book1_2.jpg", "book1_3.jpg", "book1_4.jpg", "book1_5.jpg", "book1_6.jpg", "book1_7.jpg"];
var j = 0;
When clicking on the slideshow the images cycle through.
Is it possible to let the images inside the var brackets preload, because currently they only start loading when clicking on the slideshow, which takes a lot of time in my case.
I hope you understand my question well. Thank you guys!
In this use case (if you need to load images with JavaScript) it would probably be best to append you images in to HTML when page is loaded and hide them, with CSS for example, when they shouldn't be visible.

Perform image analysis only after images are already loaded

I am looking for a way to scale images of a web page for mobile devices. My approach is to store the dimensions of each image using JavaScript, and if the screen of the user is smaller than a certain value, all images will be resized using JavaScript. My problem is that the following function does not detect if the images are already loaded, so the result would be 0 for not loaded images. My question is, how can I implement a check, so that the function will compute the image size only after the image was completely loaded? I am not using jQuery.
function storeImageSizes() {
isizes = [];
imgs = document.getElementById('content').getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
isizes[i] = [
window.getComputedStyle(imgs[i]).getPropertyValue('width').replace('px', '') * 1,
window.getComputedStyle(imgs[i]).getPropertyValue('height').replace('px', '') * 1
];
}
}
Add a listener to be called when all DOM elements load. ie:
document.addEventListener("load", (function(){
isizes = [];
imgs = document.getElementById('content').getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
isizes[i] = [
window.getComputedStyle(imgs[i]).getPropertyValue('width').replace('px', '') * 1,
window.getComputedStyle(imgs[i]).getPropertyValue('height').replace('px', '') * 1
];
}
})
Did you try image.onload?
Also, check this answer out. It highlights the use of image.onload and also avoids browser cache issues.
You can use the following solution to perform image analysis after the images are already loaded:
document.querySelector('#image').addEventListener('load', storeImageSizes);
Calling storeImageSizes() in window.load function should fix the problem
$( window ).on( "load", function() { ... })
It basically is an event which is triggered when all the images and the complete page is loaded. Since you want the function to run when all the images are loaded you should use this event.
Note the difference between document.ready and window.load.
document.ready runs when the DOM is ready where as window.load runs once the complete page is loaded i.e., images/iframes etc.
Take reference from here Simple example using Jquery

Replace Page Links on Popup Page With Javascript to Open in Main (Parent) Window

I have a popup player for my radio station website. The window has links to various other pages in my site, some of which are created dynamically by Wordpress widgets.
I want the links to open in the parent window as most of the content isn't suitable for the small popup window.
The approach I have taken is to use javascript to re-write the links as target="parent". This works (from the footer) with the following script.
<script>
var aEls = document.getElementsByTagName('a');
for (var i = 0, aEl; aEl = aEls[i]; i++) {
aEl.href = aEl.href.replace('target="_self"','target="_parent"');
}
var imgEls = document.getElementsByTagName('img');
for (var i = 0, imgEl; imgEl = imgEls[i]; i++) {
imgEl.src = imgEl.src.replace('target="_self"','target="_parent"');
}
</script>
However, this only works for static links on the page, and not those generated via my slider widget or another widget.
Is there some place this needs to be included, or an adjustment able to be made to find and replace all links after that have been generated?
Edit: To avoid confusion, I'll reiterate the requirement (my attempt was just that, an attempt). I need to re-write all the links, on load, of my popup page, to open in the main site (parent window).
Edit2: While I seem to be able to substitute target="_parent" it's not having the desired effect. Perhaps I need to somehow use window.opener. Any ideas?
Edit3: This works correctly. I think my find/replace is going to have to rebuild this function around the links somehow.
You can use this.
$('img').each(function() {
var OldSrc = $(this).attr("src");
var newSrc = OldSrc.replace('target="_self"','target="_parent"');
$(this).attr("src",newSrc);
});
This is short solve.
You cant replace attribute target, from attribute href. use el.target and just set the value
var aEls = document.getElementsByTagName('a');
for (var i = 0, aEl; aEl = aEls[i]; i++) {
aEl.target="_parent";
}

Image preloading ... the fastest way

I'm working on a project dealing with a high traffic webpage (really high!). On landing page tons of images are displayed (~40), that needs to be there, right after the page was loaded to display them by fading in. We don't use any library for this since it should be loaded before it was ready to use. We have 4 image servers. Does anybody have any experience which is the best way to load images? I tried the following:
In page header, right after the <head>, inserted a script tag:
<script>
var img = new Image(); img.src= "src of the image";
</script>
Doing so, images begin and finish to load before DOMReady and Load event. But images on the page with the same url seem to load again, even if they was loaded before. The urls are the same, caching was on, Mozilla was used.
Maybe there's some mechanism that prevents the browser to use those images? or what?
Another question: does it cause any slowdown, when DOM and images load parallel?
First, I would recommend using CSS sprites. You can find more information here:
http://www.alistapart.com/articles/sprites
Second, if you want to load the images on DOM ready, use the following:
function listen(event, elem, func) {
if (elem.addEventListener) {
elem.addEventListener(event, func, false);
} else if (elem.attachEvent) {
elem.attachEvent('on' + event, func);
}
}
listen('load', window, function() {
var img = new Image();
img.src= "src of the image";
});
Using sprites will cut your loading time in half. You eliminate the majority of your HTTP requests and the sprite sheets get cached right away so each subsequent page a user visits will already have it loaded.
EDIT
Here's a way to preload many images:
function preload(images) {
if (document.images) {
var imageArray = [];
imageArray = images.split(',');
var imageObj = new Image();
for (var i = 0; i < imageArray.length; i += 1) {
imageObj.src = imageArray[i];
}
}
}
Call the function like this:
preload('image1.jpg,image2.jpg,image3.jpg');

Changing background images, Jquery + CSS

I am working on a clients website and want the background images on the "cruise_offers" div to change, possibly only 3 - 4 images in rotation.
My jquery knowledge is quite basic so any help would be great.
I would prefer it to work with jQuery as I am using it elsewhere on the site.
My markup:
<div class="cruise_offers">
<span class="overlay_bar">
View our Great Cruise Offers
</span>
</div>
Cheers
Rory
Check out this link - I worked on something similar and it may help:
I found a jquery image rotatation script and adding hyperlinks to the images breaks the animation
$(div.cruise_offers).removeClass('cruise_offers');
$(div.cruise_offers).addClass('cruise_offers1');
create classes in your css with different background images.
Maybe something like this would work (I haven't tested it).
var current_image = 0;
var rotation_speed = 5000; //milliseconds
var where = $("div.cruise_offers");
var images = new Array();
images[0] = 'img1.jpg';
images[1] = 'img2.jpg';
function change_image() {
current_image++;
if (images[current_image].length == 0) {
current_image = 0;
}
$(where).css("background-image", "url("+images[current_image]+")")
}
if (where.length != 0) {
setTimeout("change_image()", rotation_speed);
}
Check out the Cycle plugin and visit the demos at the bottom of the page to get started.

Categories

Resources