GIF Image Stops when "document.location.href" - javascript

I have this function in javascript :
function loadPage (url){
showLoadPageGif(); // visibility On
document.location.href = getPath + "/" + url ;
}
When I use this function , GIF image is displayed in the screen but not working .
someone has fought before, with this problem ? thnx

i recently ran into this issue using animated SVGs as background-images in pseudo elements. I purposefully put in a large delay on my webserver so i could stay on the current page after window.location = url; It was weird that all other CSS animations and hovers still worked, but the SVG cog just stuck.
After some playing around i found that the animations continued to run if, instead of changing window.location, i submitted a GET form.
var url;
//load & setup loading animation
//then generate and submit form with a slight delay
setTimeout(function(){
var new_form;
new_form = document.createElement('form');
new_form.method = 'GET';
new_form.action = url;
document.body.appendChild(new_form);
new_form.submit();
}, 100)
tested on safari 5.1, firefox 24, chrome 32

I assume you mean "GIF animation stops".
This is the correct behavior. Since you go to a new page, all resources for the old page are freed. This of course includes the GIF itself.
You don't "see" this happening because the browser doesn't waste any time rendering a blank page when you assign location.href.
What you need to do is use an AJAX to request the new page and then replace the whole DOM with the new one in the success handler.
There is a bug in IE6 which stops the animations when you start an AJAX request; to fix that, just assign the src attribute of the image again (i.e. img.src = img.src;) to restart them.

Which browser you're using ? I needed to do the same one time if you're using IE just do this :
var loadingFigure = $('#myImage');
var html = loadingFigure.html();
window.location.href = 'myImage';
loadingFigure.html(html);
For firefox is more complicated you need to use an iframe and do something like this :
<iframe id="myIframe" src="/images/busy.gif" scrolling="no" frameborder="0"></iframe>
$('#myIframe').attr('src', '/images/busy.gif');
window.location.href = 'mylocation'
$('#myIframe').attr('src', '/images/busy.gif');

Related

How to use window.location with randomized objects?

I've made a site that randomizes HTML videos or images just to practice my javascript.
I am trying to make it so that each time a video is randomized the URL location will change to represent the new video, this way users would be able to link directly to a video that was randomized.
Currently it only displays a static url that does not change whenever content is loaded.
Here is the obligatory codepen
Codepen
function chooseRandomVideoFromList() {
var i = Math.floor(Math.random() * currentList.length);
var video = currentList[i];
var $video = $('video');
// clear
$video.html('');
// <source src="" type="">
video.sources.forEach(function (source) {
var $source = $('<source>').attr('type', source.type).attr('src', source.src);
$video.append($source);
});
Any help or advice would be greatly appreciated, i've read the documentation and I am still stumped :S
Thanks guys!
You cannot directly write on the window.location.href property, but you may change your sites url with the html5 history api and pushstate.
Example:
history.pushState({}, "Stackoverflow", "http://stackoverflow.com");
This should work in all modern browsers, see: http://caniuse.com/#search=pushstate
More information on this topic could be found here: https://developer.mozilla.org/de/docs/Web/Guide/DOM/Manipulating_the_browser_history
Though keep in mind you need also to listen on popstate events if you want the users to be able to use their browsers back and forward buttons. Also your server side code needs to handle the urls.
If you need to support older browsers or don't want the server side to be involved you could set the window.location.hash property instead which does not change the url itself but let you change the hash part of the current url, for example:
window.location.hash = "uri=stackoverflow.com";
This way you might store the Index of the video currently shown. When loading the page you might want to check if there's a value in "window.location.hash" and if it is a valid index for your videoFiles. If so you should play that video.
Example (insert in your starting code):
if (window.location.hash !== "") {
showSpecificVideoFromList(window.location.hash);
}
And this one in your chooseRandomVideoFromList:
window.location.hash=i;
Then implement your showSpecificVideoFromList in order to show the given index (and check for validity)

detecting img loads in javascript

I have a function where I get the img src value as the parameter, what I want to do is check to see if that image loads with a 200 ok or 404/some other error. If it gets a 200 ok, then I want to inject an img tag with that src into the DOM(I reason that during checking,it also gets loaded into the browser cache and injecting that img tag into the DOM loads it from the cache ). I tried with a simple snippet of code as follows :
function checkImage(src)
{
var img = new Image(),
tag = '<img src="'+src+'" />',
alt = '<span>sorry,image broken</span>';
img.onload = function(){
$('.some-container').html(tag);
};
img.onerror = function(){
$('.some-container').html(alt);
};
img.src = src;
}
It worked fine in chrome, but went havok in firefox and ie(both of them are firing only the error event no matter whether the image loaded fine or broke). Instead of using onload and onerror, I tried it using jquery like :
$(img).load(...).error(...).attr('src',url);
$(img).on('load',...).on('error',...).attr('src',url);
$('<img />').load(...).error(...).attr('src',url);
$('<img />').on('load',...).on('error',...).attr('src',url);
and even tried the jquery.imagesLoaded plugin by desandro(https://github.com/desandro/imagesloaded) like :
$(img).imagesLoaded().done(...).fail(...);
$(img).imagesLoaded().progress(function(instance,image){
image.isLoaded?alert('loaded'):alert('broken');
});
$('<img />').imagesLoaded().done(...).fail(...).attr('src',url);
$('<img />').imagesLoaded().progress(function(instance,image){
image.isLoaded?alert('loaded'):alert('broken');
});
I also tried the solutions from :
jQuery callback on image load (even when the image is cached)
https://groups.google.com/forum/#!topic/jquery-dev/7uarey2lDh8
but as it turns out, works in chrome, but not in FF or IE, is there any solution where I can check for an image which is present in memory but not in the "DOM" ? Thanks in advance.
You have to check for image onload after setting a source to it.
var img = new Image();
//set source to the image
img.src = "set/image/source/path"
img.onload = function(){
//if image load is successful
//create an jQuery object out of this image
var jQimage = $(this);
$('.myContainer').html(jQimage);
}
Also note that jQuery load function cannot guarantee you a cross browser check for image loading as mentioned in jQuery docs
So, the best approach is to check onload with native javascript and create an jQuery object if necessary to make use of jQuery methods.
Have a look at what w3schools has to say about the Image() javascript object.
http://www.w3schools.com/jsref/dom_obj_image.asp
onabort - Loading of an image is interrupted, W3C YES
onerror - An error occurs when loading an image, W3C YES
onload - An image is finished loading, W3C YES
also the complete property of the Image() object, determines if the browser is finished loading an image, Unfortunately this particular property is not W3c
hope that helps a little
PS: After having a little Google search I found this Q/A from Stack overflow.
Cross-browser image onload event handling

How can i Check if <object> failed to load?

I have the following code:
document.getElementById("launcherDiv").innerHTML =
"<object id='launcher'
classid='CLSID:17E88883-3488-46B8-BE4D-30568888855'
codebase='Helper.CAB#version=8,8,8,88'>
</object>";
Let say the download/installing failed,
How can I know this? depending of it that I can't know how much time it supposed to take..
If I will check in a loop how can I know when to end?
previously I used to define the tag inside the HTML and it waiting until the installation finished or failed.
But now I need delay loading of this ActiveX so I can't use this
Can anyone help me?
If object tag is failed to load then it will render inner HTML between tag. For example
<object data="my/file/path.pdf">Object not supported</object>
If object fails then it will show inner text i.e. "Object not supported"
Maybe this helps:
var iv = setInterval(function () {
if (document.all["launcher"].readyState == 4) {
clearInterval(iv)
alert("Object loaded")
}
}, 100);
What it does is set an interval which checks the readystate every 100 seconds and if the object has loaded it alerts.
I know this is a old post but I was trying something like this my self.
In the object tag you can do something else inside it.
For example I was making a music site and If the custom player didnt load I wanted the audio tag to take over.
example:
<object>
<load customplayer> <!--==If this fails do the next line ==-->
<audio>
load song
</audio>
</object>
The only difference between the (first) anchor in an object that successfully loaded embedded content and the fallback content (first) anchor in an object that did not successfully load are the dimensions of the element. So all you have to do is determine your policy of the element you use for fallback (this is very likely an anchor element though some people might still support Flash as fallback content) and then target that element and get it's height in example; if the height is greater than 0 the object element did not successfully load.
var o = document.getElementsByTagName('object');
console.log(o[0].getElementsByTagName('a')[0].getBoundingClientRect().height);

<img src> w/ timeout?

I have some tracking pixels on our site, that I'd like to protect against them impacting our user experience if their servers are down or slow. What's the easiest way to specify a maximum time the browser should attempt to load a given img - i.e. try for 100ms and then give up? (I'd rather not track a given customer than have a server hang on the third-party server impact our site).
You could insert the <img> with JavaScript and use setTimeout() to remove it after 100ms.
Example with jQuery:
var tracker = $("<img>", { src: trackingUrl }).appendTo(document.body);
setTimeout(function() { tracker.remove(); }, 100);
you should load them when the document is ready.
or at the lastline ( in the html). this way- it wont hurt the user experience.
document ready can be also used with jQuery.
but you can use window.load.
as a rule(not always) - all scripts should be at the end of the page.
if you want to FORCE time out KILL :
create an img tag.
attach the load event to the img (this function will set flag : downloaded=1;)
set the src.
with setTimeout Function your gonna kill the img.
how ?
if after X MS the downloaded ==0 then kill.
so : each load event( from the IMg) is setting a flag ( downloaded=1).
your timeout function dont care about nothing!!! after x MS she going to kill the img - only if the downloaded==0.
You would have to use javascript to do this, there's nothing native to HTML/HTTP that would do this on a page basis. Google around for "HTML IMG timeout".
as img.parentNode.removeChild(img)
Not all img have containers.
var img = new Image()
img.src = '...third-party server...'
setTimeout(function() {
img.removeAttribute('src')
}, 100)
You could call a server process in the IMG tag. Let it worry about timing out the load.

Changing <img src="XXX" />, js event when new image has finished loading?

I have a photo gallery web page where a single <img src="XXX" /> element's src is changed (on a click) with JavaScript to show the next image—a poor man's ajax I guess. Works great on faster connections when the new image appears almost immediately. Even if it takes a few seconds to load, every browser I've tested it on keeps the old image in place until the new one is completely loaded.
It's a little confusing waiting those few seconds on a slow connection, though, and I'm wondering if there's some JavaScript event that fires when the new image is done loading, allowing me to put a little working... animated gif or something up in the meantime.
I know I could use AJAX for real (I'm using jQuery already), but this is such a nice and simple solution. Besides this lag, is there any other reason I should stay away from this approach to changing images?
You can set up a handler on the "load" event.
$('img.whatever')
.load(function() { /* do stuff */ })
.attr('src', newURL);
Actually I guess you'd want to do this with "live()":
$('img.reloadable').live('load', function() { $(this).show(); });
// ...
$('img#someId').hide().attr('src', newURL);
edit — whoa, where did that year go? Well, it turns out that one problem with that "live" approach I typed in way back when is that the "load" event does not bubble. Now what you can do, however, is leverage the way that "Image" objects (as opposed to <img> DOM elements) behave. Basically, the function that changes the URL can use an "Image" element as the place to keep the handler. The code that changes the actual "src" attribute of the real <img> tag would then also update the "src" of the "Image" object instance. The browser will only really load the image once (assuming cache control is all cool), but the browser will still call the "onload" handler of the "Image":
(function() {
var imageObj = new Image();
imageObj.onload = function() {
// code to run when image loads from server
};
$('#hypotheticalButton').click(function() {
$('#imgToUpdate').attr('src', newURL);
imageObj.src = newURL;
});
})();
You just just preload the images with jQuery so that way when the user clicks, the next image is already loaded and there shouldn't be a delay...that is unless the user goes to your page, and starts clicking on the image before they are loaded.
http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript
var slideimg = $('#slideimage');
slideimg.click(function(){
var img = new Image();
var url = 'url_to_next_image.jpg';
$(img).bind('load',function(){
$('#loading').hide();
slideimg.attr('src',url);
}).attr('src',url);
$('#loading').show();
});
This should work even with IE's crazy cache handling.

Categories