I have a large gif animation on a web page and want to start it not until it's completely finished loading. How would that be possible using JavaScript / jQuery?
Use a placeholder image, and replace it with the animated GIF once that GIF is fully loaded:
<img id="anim" src="placeholder.gif">
JS:
var myanim = new Image();
myanim.src = '/img/actions.png';
myanim.onload = function() {
document.getElementById('anim').src = myanim.src;
}
http://jsfiddle.net/mblase75/6XTg7/
You can hide GIFs with CSS (or JS replacing them with a placeholder) and when GIFs are loaded you can fire show()
$('img[src$=".gif"]').load(function(){$(this).show())
You could hide it until it is fully loaded.
<!--- this uses jquery !-->
<script type="text/javascript">
var image_url = "http://media.tumblr.com/tumblr_m4doax3R071r9c1z7.gif";
var image = $('<img />').load(function(){
$(this).show();
}).attr('src', image_url).hide();
$('body').append(image);
</script>
The issue here is that once the image has been downloaded (i.e it is in the browsers cache), there really doesn't seem to be any way of starting it from a particular frame.
You have no control over gif animation through javascript, so you have to implement some sort of a hack. You have to make it hidden in the beginning. Instead of the actual picture you can put a div with the dimensions of the actual picture and with text like "wait".
When the image is downloaded in the browser you can substitute div with an image. And at that point of time animation will start
Related
I'd like to make GIF's only starting to play once they are actually on the screen. I came up with a small JS Script that basically replaces a static image (the first frame of the gif) with the actual gif, as soon as the image is on the monitor.
I can't really change that much in the HTML section since i'm working in a CMS.
HTML:
<div class="lazy">
<img src="firstframe.png">
<img src="gif.gif">
</div>
JS:
var lazies = $('.lazy');
lazies.each(function(){
var src = $(this).find('img').eq(1).attr('src');
if($(this)[0].offsetTop <= window.innerHeight && !$(this).hasClass('lazyactive')){
$(this).find('img').eq(0).attr('src', src);
$(this).find('img').eq(1).hide();
$(this).addClass('lazyactive');
}
})
window.onscroll = function(){
lazies.each(function(i){
if(window.pageYOffset + window.innerHeight >= $(this)[0].offsetTop && !$(this).hasClass('lazyactive')){
var src = $(this).find('img').eq(1).attr('src')
$(this).addClass('lazyactive');
$(this).find('img').eq(0).attr('src', src);
$(this).find('img').eq(1).hide();
}
})
}
The code works fine as long as i have different GIF's on the page.
But as soon as i have the same GIF multiple times on the page, i have a problem. Every time one of the PNG get's replaced with the GIF (by scrolling down), every GIF starts to play from beginning.
I'm not sure if that's normal behaviour of the browsers or the error is in my script..
I have a problem with a mouseover script. Everything works as it should but I have a small issue that I don't know how to solve. More precisely, the mouseover script creates a grayscale image hover effect. When the page loads the colored images are showing for a short time (1 second or less) and then the javascript is applied and they are all grayed out which is exactly how things should work.
How can I make it so that the colored images will not appear before the javascript is applied? Basically, I want the grayscale images to appear when the page loads not after. Is it possible?
You can see the script here and the webpage in question here.
I would remove the images from the HTML and load them dynamically.
I would use <a class="placeholder" href=""></a> as placeholders for the <img src="" /> and would style the links to either be hidden or go well with the design.
$('a.placeholder').each(function() {
var src = $(this).attr('href');
var image = new Image(); // this is not yet visible in the DOM.
image.onload = grayscale; // change the grayscale function to accept
// event parameters
image.src = src; // this triggers the onload event which
// grayscales the image
var dom_image = $('<img />').attr('src', src);
$(this).replaceWith(dom_image);
});
Of course you have to be doing the above on document ready not on window load.
I noticed that when I do something like this (with jQuery, but I don't think it matters):
$("#myDiv").html("<img src='/image.png'/> this is my image.");
The browser displays the text first, and then the image is loaded, and shifts the text to the right which creates a horrible flickering effect.
The image doesn't appear to be cached by the browser. Any idea why ? How can I avoid this phenomena when loading images into the DOM ?
How can I avoid this phenomena when loading images into the DOM ? there are two major methods (may be more :))
1) Set the actual size of the img <img with='20' height='20' src='...' /> or via CSS style.
2) Use image preload and insert your code only when image is loaded
var img = new Image();
$(img).load(function(){
$("#myDiv").append($(this))
.append(document.createTextNode("this is my image.");
// or your way, browser should take image from cache
$("#myDiv").append("<img src='/image.png'/> this is my image.");
}).attr('src', '/image.png');
ps: there is a serious bag in SO engine - code formatting does not want to combine with numbered listing. So I removed the list.
Preload the image before attaching it:
$("<img>", {
load: function() {
$("#myDiv").empty().append( this, "this is my image." );
},
src: "/image.png"
});
preload your images like this
var images = [
'/path/to/some/image1.png',
'/path/to/some/image2.png'
];
$(images).each(function() {
var image = $('<img />').attr('src', this);
});
Images may render a little slower that text, even if cached. If you know the dimensions of the image add height and width attributes to the image and then it won't jump around.
I cannot get animated gif to display before flash movie loads. I am using this script but does not seem to work. I do not want to use a flash loader.
<script type="text/javascript">
var image = new Image();
image.src = 'http://www.hmaimages.com/MN/flash_loader/loading.gif';
</script>
Any help be much appreciated.
You don't need javascript for this.
Simply wrap and flash file in a div and give it a background image:
div {background:url(loading.gif) no-repeat center center;}
Is it possible to load a background-image asynchronously?
I've seen many jQuery plugins to load normal image in an asynchronous way, but I can't find if it's possible to preload / asynchronously load a background-image.
EDIT
I clarify my problem. I've been working on this test site http://mentalfaps.com/
The background image is loaded randomly from a set of images refreshed each hour by a chron job (which takes random images on a flickr catalog).
The host is free and slow at the moment, so the background image takes some time to load.
The positioning of the first overlay (the one with the PNG transparent mentalfaps logo) and width are regulated by a function created in the jQuery(document).ready construct.
If you try to refresh the page many times, the width of the right overlay div is 0 (and so you see a "hole" in the layout)
Here is the method to set my positions:
function setPositions(){
var oH = $('#overlay-header');
var overlayHeaderOffset = oH.offset();
var overlayRightWidth = $(window).width() - (overlayHeaderOffset.left + oH.width());
if (overlayRightWidth >= 0) {
$('#overlay-right').width(overlayRightWidth);
} else {
$('#overlay-right').width(0);
}
var lW = $('#loader-wrapper');
lW.offset({
left: (overlayHeaderOffset.left + oH.width() - lW.width())
});
}
The problem is that the $(window).width() is lower then the effective window width! so the check fails and the script goes for $('#overlay-right').width(0);
any ideas?
Not sure whether I really understand your question, but background images (and all other images) are already loaded asynchronously - the browser will start separate requests for them as soon as it encounters the URL while parsing the HTML.
See this excellent answer for background on loading order: Load and execution sequence of a web page?
If you meant something else, please clarify.
The trick to loading something in the background is to load it once, so the next time when it is loaded it already is in the cache.
Put the following at the end of your html:
<script>
var img = new Image();
img.onload = function () {
document.getElementsByTagName('body')[0].style.backgroundImage = 'background.png';
};
img.src = 'background.png';
</script>
You could use a prefetch link in the head.
<link rel="prefetch" href="/images/background.jpg">
You should be able to add these links to the head via JavaScript.
I like to use CSS to fill the background with a color for page load.
After DOM ready event, I use jQuery to modify the CSS and add a background image. That way, the image isn't loaded until after page loads. Not sure about async, but this method gives the user a decent experience.
Example: http://it.highpoint.edu/
The right side navigation links have a background image. The page initializes with a background color. It is replaced with a background image after page load, via jQuery.
changes in this file jquery.ImageOverlay.js
set your height and width and enjoy this...
imageContainer.css({
width : "299px",
height : "138px",
borderColor : hrefOpts.border_color
});
As it is already mentioned, the background image is loaded asynchronously. If you need to load the background image from JQuery code you may also set the addClass() method to set a CSS class or attr("style=\"background-image:url('myimage.png')\"")
Ive found the answer myself, it was a problem due to the .offset() method that gived sometimes the wrong values.
I had the write values using the .position() :
var overlayHeaderOffset = oH.position();