Preloading content with images with jQuery - javascript

I am using .load() in jQuery to load in html content, but in this content there are 3/4 images embedded. The success event only fires on .load() when all the html is loaded in and not actually the images, does anyone know a way of preloading the full content of a page?
$('#ajax_loader').hide().load('page.html',function(){
$(this).fadeUp(1000);
});
This is my simple code (rest of it is in the full app), loading in the following code (ie. page.html)
<div>
<div id="slideshow">
<img src="images/img1.jpg" />
<img src="images/img2.jpg" />
<img src="images/img3.jpg" />
</div>
<p>This is some sample content</p>
</div>

I suggest that you don't use a fadeIn animation after the images are loaded because of performance degradation it brings. It is usually a good idea to fadeIn the content then start loading the images to ensure that the animation is smooth for as many users as possible.
Having said that, of course you can accomplish your original goal if you want to stick with it:
Use a 1x1 blank image as the image src attribute and store the real url in the title.
<div>
<div id="slideshow">
<img src="blank.gif" title="images/img1.jpg" />
<img src="blank.gif" title="images/img2.jpg" />
<img src="blank.gif" title="images/img3.jpg" />
</div>
<p>This is some sample content</p>
</div>
And your code becomes:
$('#ajax_loader').hide().load('page.html', function(){
var c = 0;
var images = $("#slideshow img");
images.load(function(){
if (++c == images.length) {
$('#ajax_loader').fadeIn(1000);
}
});
images.each(function(){
this.src = this.title;
});
});

The images are loaded with separate HTML requests, and obviously the browser can't even start loading them until the HTML in the response has been parsed.
If you know the URLs of the images before you load the content, then you can preload them by creating "Image" elements and waiting for them to load (that is, by handling their "load" events individually).
var imgUrls = [ "images/img1.jpg", "images/img2.jpg", "images/img3.jpg" ];
var c = 0;
for (var i = 0; i < imgUrls.length; ++i) {
var img = new Image();
img.onload = function() {
c += 1;
if (c == imgUrls.length) {
// at this point all images are loaded
// ...
}
};
img.src = imgUrls[i];
}
edit — #galambalazs pointed out that the closure around the handler was (in this case) unnecessary.

Check out this similar situation
It seems that the main fix to your problem would be the correct use of the .ready and the .load operator. If used properly, you can wait until all elements and media items are loaded into the browser before a response is passed to its handler. I don't want to plagerize too much :) and its a really great answer.

Related

Problem with adding images in loop in html executed from javascript

I'm trying add images in "for" loop
<div id="p_0" style="text-align:right">
<picture style="text-align:right;visibility:visible">
<img src="~/lib/images/Wisielec1.png" alt="Wisielec" style="width:100px;margin-left:inherit">
</picture>
</div>
#for(int i = 1; i < 6; i++)
{
<div id="p_#i" style="text-align:right">
<picture style="text-align:right;visibility:visible">
<img id="pi_#i" src="" alt="Wisielec" style="width:100px;margin-left:inherit">
</picture>
</div>
}
so in JavaScript I have
var images = ['Wisielec1.png', 'Wisielec2.png', 'Wisielec3.png', 'Wisielec4.png', 'Wisielec5.png', 'Wisielec6.png' ];
document.getElementById("pi_" + j).src = "~/lib/images/"+ images[j];
But when I'm loading page there is no images in folder /lib/images visible in Developer tools.
Do I have to attach this folder somewhere so that the pictures are uploaded to the server?
I can see pictures only when I enter the path of a specific picture in html code. In console I have error :
Yes, I'm getting error "Wisielec2.png:1 GET https://localhost:44320/Home/~/lib/images/Wisielec2.png 404
This looks wrong:
"~/lib/images/"
Why are you using a ~ at the start of the path? Notice what it does to the URL:
https://localhost:44320/Home/~/lib/images/Wisielec2.png
This has nothing to do with the code you're writing, you're simply using an incorrect URL. If /Home is in the root of your website then just use that:
"/Home/lib/images/"
Or perhaps use a relative path based on where you're calling it from:
"../lib/images/"
Basically you need to determine what the actual correct URL is for your images and use that.

jQuery fullPage: All images loading at same time

I use jQuery fullPage on my website, and everything looks just fine. The problem I'm having is that all images are loaded at "same time" making the website's load to be around 23Mb!!!
I tried reading fullPage's documentation, but couldn't make images load like "lazy load" or something.
All of them are loaded as a background:
<div class="slide" id="slide2" style="background-image:url(produtos/002.jpg)">
</div>
Do you have any clue so I can load images as needed and not all at the same time?
Things are easier :)
Just use conditional CSS based on the class fullpage.js adds to your body element. (fp-viewing-section-slide). If you need more information about it you can check this video where it is explained with more detail.
For example:
.fp-viewing-secondPage-0 #slide2{
background-image:url(produtos/002.jpg)
}
.fp-viewing-3rdPage .section{
background-image:url(produtos/1.jpg)
}
This way the background image will only be loaded when the section enters in the viewport.
Another way of doing it is by using the active class added to the section or slide you are in:
#slide2.active{
background-image:url(produtos/002.jpg)
}
.section.active{
background-image:url(produtos/1.jpg)
}
Or you can even decide to preload the backgruonds of all the slides within a section when arriving to the section itself (rather than to the specific slide) by doing this:
.section.active #slide2{
background-image:url(produtos/2.jpg)
}
.section.active #slide3{
background-image:url(produtos/3.jpg)
}
.section.active #slide4{
background-image:url(produtos/4.jpg)
}
Update
You can create an asynchronous function which preloads images while the rest of your script continues to run.
Example with background images:
<body>
<div class="container">
<div class="slide" id="slide1"></div>
<div class="slide" id="slide2"></div>
<div class="slide" id="slide3"></div>
<div class="slide" id="slide4"></div>
<div class="slide" id="slide5"></div>
<div class="slide" id="slide6"></div>
</div>
</body>
<script src="https://code.jquery.com/jquery-2.2.0.min.js" type="text/javascript"></script>
<script>
console.log('Creating images.'); // Will log first
setTimeout(function() {
createImages();
console.log('Image load complete.'); // Will log last
}, 0);
function createImages() {
var n = $('.slide').length;
for (var i = 1; i <= n; i++) {
$('#slide'+i).css('background-image', 'url(produtos/00'+i+'.jpg');
}
}
console.log('Continuing script.'); // Will log second
</script>
jQuery's setTimeout(), when set to 0 milliseconds, will emulate an asynchronous function that will run parallel to the rest of your script. This way your page will load immediately and then load images as they're ready. The above example assumes you've named your files in order starting at 001.
I hope this helps.
jqueryjavascriptasyncdom

Making an image change from one to the next in 2 seperate divs

I am trying to create two divs with a rotating image in on my webpage, these change to another image after a certain amount of seconds and there are 3 images to display. At the moment I am just trying to get the mechanics of this working using the code below, but although its simple I can not get it working. the code is the same as what I have used before however this time it does not want to work. I did it last, years agao, and I have completely forgotten how and research has not helped.
My code is below. In case this problem is site specific I have also included a livelink HERE which I shall remove once the question is answered. THE TWO DIVS ARE THE RED AND YELLOW BOXES.
JAVASCRIPT
var rotators = [
{ id: 'advert1', images: ['http://www.w3schools.com/html/html5.gif', 'http://www.w3schools.com/html/pic_mountain.jpg', 'http://www.w3schools.com/html/pic_graph.png'], selectedIndex: 0 },
{ id: 'advert2', images: ['http://www.w3schools.com/css/klematis_big.jpg', 'http://www.w3schools.com/css/klematis2_big.jpg', 'http://www.w3schools.com/css/klematis3_big.jpg'], selectedIndex: 0 }
];
var updateImages = function() {
for (var i=0; i < rotators.length; i++) {
var rotator = rotators[i];
rotator.selectedIndex++;
if (rotator.selectedIndex >= rotator.images.length) {
rotator.selectedIndex = 0;
}
document.getElementById(rotator.id).src = rotator.images[rotator.selectedIndex];
}
};
var timer = setInterval(updateImages, 1000);
</script>
HTML
<div id="main">
<div id="advert1"></div>
<div id="advert2"></div>
</div>
You are trying to set the div src. you need to have an image (img) element inside each div and then to set the image src.
<div id="main">
<div>
<img id="advert1" alt="" src.../>
</div>
<div>
<img id="advert2" alt="" src.../>
</div>
</div>
Another option will be to set the div background image using the style property or class property (both using CSS sets with JavaScript).
The javascript is executed where you write, if you write before element then the element does not exist.
You can attach code to onReady event of document or puts code after element.
Looking at your code in Google Chrome, I see the following error in the console :
Uncaught ReferenceError: $ is not defined | new.html:204
It seems like you forgot to include the jQuery in your html page.
You can get it from a CDN on the following page: http://code.jquery.com/
Another problem is that you're trying to update an img but your DOM element is a div.
You should replace the following code:
<div id="main">
<div id="advert1"></div>
<div id="advert2"></div>
</div>
With:
<div id="main">
<img src="" id="advert1" />
<img src="" id="advert2" />
</div>

Is this preloader working? It's not being used to show status, just speed up possible image loading for later

I've been reading up on the best way to handle images for a website (which cycles through images to display when a user clicks an element) and it seems a preloader is advantageous.
Given you can take out the preloader and the current setup will simply insert image1 into the div anyway from the array, is the preloader working by including all potential HTML requests at the start, therefore reducing potential loading time later, or is this a useless implementation as it's written?
Should I actually be taking the images from the imageObj in the .append(...) ?
-NOTE - I'm aware that I'm only actually allowing the calling to image1 as it is, but this is just a practise.
HTML
<body>
<a href='#' id="image1">
Click for image 1
</a>
<hr/>
<a href='#' id="image2">
Click for image 2
</a>
<hr/>
<a href='#' id="image3">
Click for image 3
</a>
<hr/>
<a href='#' id="image4">
Click for image 4
</a>
<div id="image">
</div>
</body>
JavaScript/jQuery
// JavaScript Document
function preloader()
{
var i = 0;
imageObj = new Image();
images = new Array();
images[0]="images/image1.jpg"
images[1]="images/image2.jpg"
images[2]="images/image3.jpg"
images[3]="images/image4.jpg"
for(i=0; i<=3; i++)
{
imageObj.src=images[i];
}
}
$(document).ready(function(){
preloader();
$('#image1').click(function(){
alert("Handler for #image1 .click() called.");
$('#image').append('<img id="theImg" src=' + images[0] + ' />');
});
});
The effect of this code is to just "touch" each possible image so it gets loaded into your cache but not your DOM if that makes sense.
Should I actually be taking the images from the imageObj in the .append(...) ?
No, that part is just to force the get to preload the image into your browser cache. Notice how it is overwritten almost immediately in the loop.
If you want blistering load speeds then also consider having your images come from multiple subdomains or a CDN.

Div Swap with Timed Interval ensure pairing

I've review some similar questions, but I can't seem to find an answer to tie this all together. I am looking for a way to create a slideshow where images and a corrosponding block of text change every 10 seconds. (Below, when I state Rotate, i do not mean turn on an angle, I mean change from one visible slide to another)
For further clarification, lets call one block of text and one image a "pair". The block of text is contained in one and the image is contained in another . For this slideshow, I will have 10 pairs.
I can easily rotate an image inside utilizing a simple time delay javascript, but if I utilize a similar javascript to rotate the text, sometimes the Image and Text get out of sync with each other (don't change at same time.)
So.... my question is a 2 part question.
1.) Am I approaching this in the correct way, and if so, how do I ensure the text and images stay as pairs and rotate at the same time.
2.) Instead of rotating the content inside of the same div, should I create 10 div pairs (20 total) and create a script just to make 2 of the 20 visible at the same time? if so... any ideas on the script to do so?
Currently, I am using the following script to swap images:
<!--- Start Image Cycler Script --->
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
var timeDelay = 10; // change delay time in seconds
var Pix = new Array
("images2/slide_pics/92028.png"
,"images2/slide_pics/92026.png"
,"images2/slide_pics/92027.png"
,"images2/slide_pics/92534.png"
,"images2/slide_pics/92034.png"
,"images2/slide_pics/92555.png"
,"images2/slide_pics/92700.png"
,"images2/slide_pics/A73495.png"
,"images2/slide_pics/92701.png"
);
var howMany = Pix.length;
timeDelay *= 1000;
var PicCurrentNum = 0;
var PicCurrent = new Image();
PicCurrent.src = Pix[PicCurrentNum];
function startPix() {
setInterval("slideshow()", timeDelay);
}
function slideshow() {
PicCurrentNum++;
if (PicCurrentNum == howMany) {
PicCurrentNum = 0;
}
PicCurrent.src = Pix[PicCurrentNum];
document["ChangingPix"].src = PicCurrent.src;
}
// End -->
</script>
<!--- End Image cycler Script --->
<img name="ChangingPix" src="images2/slide_pics/92028.png" alt="" width="570" height="346" class="head-pic" />
(Sorry, my last comment decided to post itself)
As Kevin Nelson suggested, I would simply put the image and text in the same containing "block".
<div id="slider">
<div class="slide">
<img src="#" alt"this is the image" />
<p>This is the description for this particular slide</p>
</div>
<div class="slide">
<img src="#" alt"this is the image" />
<p>This is the description for this particular slide</p>
</div>
<div class="slide">
<img src="#" alt"this is the image" />
<p>This is the description for this particular slide</p>
</div>
</div>
That way you do not run into any issues with the text and images getting out of sync. There are plenty of free content/image sliders out there. I have been using Slides.js for client work as of late. It is really easy to set up and customize to your liking. It also has plenty of options (e.g. pause on hover, auto play).
Maybe I'm misunderstanding the question, but if you want to rotate text and images at same time, why wouldn't you create blocks and rotate the entire block. See this page:
http://rhmachine.flashfirehosting.com/
If I'm understanding the question correctly and you want something like that, let me know and I'll post the jquery plugin that I'm using to do it.

Categories

Resources