Image reload causes flicker only in firefox - javascript

I'm creating a website which streams real time data images from a remote system and displays them on the website. These images change at the remote site every 5 seconds and hence we auto reload/refresh these images.
PROBLEM : The image refresh takes place correctly & smoothly on IE and chrome, but in Firefox every auto refresh causes a flicker. This is unwanted behavior. How do I fix this?
PS I am using joomla articles within which I embed the required javascript
<center>
<img id="pic" src="images/CB1.jpeg" border="0" width="700" height="700"/></center>
<script language="javascript" type = "text/javascript">
function refresh()
{
document.images["pic"].src = "images/CB1.jpeg" + "?" + new Date().getTime();
}
window.onload=function(){
setInterval(function(){refresh()}, 5000 );
}
</script>
This is script is embedded in joomla articles. The image is around 300~350 KB.

Without being able to test on your machine, I can't say for certain but I think Cobra_Fast is correct in that the image is rendering before it's finished loading. To get around this, make sure you don't replace the old image until after the new image has finished loading. This should work:
<img id="pic" src="images/CB1.jpeg">
<script language="javascript" type = "text/javascript">
function refresh() {
// create new image obj
var image = new Image();
// replace the existing image once the new image has loaded
image.onload = function () {
document.images["pic"].src = image.src;
}
// set the source of the new image to trigger the load
image.src = "images/CB1.jpeg" + "?" + new Date().getTime();
}
window.onload=function(){
setInterval(function(){refresh()}, 5000 );
}
</script>

Related

How do I change a .gif file to a .png file after a couple of seconds using javascript?

I have this line of HTML in my code:
<img src="https://mundonewimpact.com.br/wp-content/uploads/2018/10/MNI-Logo-3.png" id="site-logo" alt="Mundo New Impact">
and what I want to do is that, everytime an user loads any page from my website, this img loads a .gif file (which is: https://im3.ezgif.com/tmp/ezgif-3-d8b13ba46bfb.gif) for a couple of seconds, enough for its animation to finish, and then replace this .gif file to the original .png file.
I tried using this piece of javascript code, but it doesn't work:
function play(){
var img = document.getElementById("site-logo");
if (img.src = "https://mundonewimpact.com.br/wp-content/uploads/2018/10/MNI-Logo-3.png"){
img.src = "https://im3.ezgif.com/tmp/ezgif-3-d8b13ba46bfb.gif";
}else{
img.src = "https://mundonewimpact.com.br/wp-content/uploads/2018/10/MNI-Logo-3.png";
}
setTimeout(function(){end()},10000);
}
function end(){
document.getElementById("site-logo").src = "https://mundonewimpact.com.br/wp-content/uploads/2018/10/MNI-Logo-3.png";
}
What am I doing wrong? I am a total noob so help me please!
You need to call play()in order to run the function.
You also have mistakes like if (img.src = ... instead of if (img.src == ....
I would work with event handlers, like, show the GIF animation and when the document ready event triggers, change the GIF to a different image.
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var img = document.getElementById("site-logo");
img.src = "https://mundonewimpact.com.br/wp-content/uploads/2018/10/MNI-Logo-3.png";
});
</script>

How to refresh image source only if new image is actually available?

<!--WunderGroundRadar-->
<script type = "text/javascript">
setInterval(function refreshRadar() {
   document.getElementById("content14").src = "http://api.wunderground.com/api/MyAPIkey/animatedradar/q/autoip.gif?&radius=90&num=15&delay=20&width=430&height=500&smooth=1&newmaps=1&interval=15&rainsnow=1"
  }, 900000);
</script>
I use the code above to refresh a weather radar .gif image on my website about every 15 minutes. This normally works great, but sometimes when the refresh takes place the image is broken from it's source and my site has a broken image icon until the next refresh takes place approx. 15 minutes later. I would like to set this up so that if the requested image is broken or not available at the time that the refresh function runs, I keep the image that is already loaded instead of replacing it with a broken image icon. I am willing to use any javascript or Jquery that might achieve this, but I am a novice programmer, so if you could break down any intricate code that would be much appreciated. Thanks!
You can try something like this
<script type = "text/javascript">
setInterval(function refreshRadar() {
img = new Image();
img.onload = function(){
document.getElementById("content14").src = img.src;
};
img.src = "http://api.wunderground.com/api/MyAPIkey/animatedradar/q/autoip.gif?&radius=90&num=15&delay=20&width=430&height=500&smooth=1&newmaps=1&interval=15&rainsnow=1"
}, 900000);
</script>
it attempts to load source to a temporary image and only on successful load assings source to "content14"

how can I asynchronously load an image on page load and display a loading gif while it loads?

Here is my image tag. The image is graph that is generated dynamically from the database. The amount of data involved can vary by a lot. Sometimes it loads in less than a second and other times it can be up to 6 or 7 seconds until the graph image is returned and displayed. What I want to do is display a simple place holder gif until that actual image in loaded.
<img src="#Url.Action("Graph", new { id = Model.ID })" alt="Graph is Loading..." />
Disregarding your ASP completely, you can add the element with the loader as the source and the real image as a data attribute, then load the image with javascript, and swap images once the real image has loaded:
<img src="loader.gif" data-src="/images/menubar.png" />
JS preloading
$('img').each(function() {
var self = this,
src = $(self).data('src'), // get the data attribute
img = new Image(); // create a new image
img.onload = function() { // onload
self.src = this.src; // swap the source
}
img.src = src; // set source of new image
if (this.complete) $(this).load();
});

how to remove delay in image loading in html?

I create a web page and put an img tag on this page. the img.src is the url of the image from the network IP camera. It works but the stream I get have delays. I understand this delay is because I load the image and loading image takes some time. my question is how can I minize these delay. I do the following;
<script language="Javascript">
x = document.getElementById("stream");
intervalID = setInterval(LoadImage, 0);
function LoadImage()
{
x = document.getElementById("stream");
x.src = "http://IP:PORT/jpg/image.jpg";
}
</script>
<img id="stream"
width="640" height="480"
alt="Press reload if no video displays"
border="0" style="cursor:crosshair; border:medium; border:thick" />
<button type="button" id="btnStartLive" onclick="onStartLiveBtnClick()">Start Live</button>
I've just found your question in the unanswered section and decided to give it a go. The following script creates an internal <img> tag (with new Image()), assigns the necessary attributes, then sets an onload "event handler" attribute, which checks when the image loaded. When that function is called, the #stream is replaced by the new internal image tag.
In case the #stream is not directly inside the body tag (i.e. inside another element like a <div>), edit streamParentElement to point to the image's parent element.
I added a ?nocache query parameter to the string, because while I was testing the code, I found out that the image tag was changing but the visible image stayed the same. I also added a loadDelay, because the images on my client were loading too fast, and it got to the point where it crashed my browser. I advise you to not lower that value below 50. Live demonstration of this code here
<script language="Javascript">
var streamParentElement = document.body, loadDelay = 200;
setTimeout(MakeImage,1);
function MakeImage(){
var img = new Image();
img.src = "http://IP:PORT/jpg/image.jpg?nocahce="+new Date().getTime()+Math.random();
img.width = 640;
img.height = 480;
img.style.border = 0;
img.style.cursor = 'crosshair';
img.id = 'stream';
img.onload = function(){
var stream = document.getElementById("stream");
streamParentElement.insertBefore(img,stream);
stream.outerHTML = '';
setTimeout(MakeImage, loadDelay);
};
}
</script>
<img id="stream" alt="Press reload if no video displays" />
create your html page. eg:
<html>
<head>
<title>
Some Page
</title>
</link rel="stylesheet" href="path to your css file"/>
<script type="text/javascript" src="path to you javasctipt file"></script>
</head>
<body>
<h1 onClick="javascript:someFunction()">
Click here
</h1>
</body>
</html>
you can then create many other "someFunction" functions. They all just reference the AJAX function.this is just to make typing a little less...
The easiest ajax way:
var path;
var div;
var xmlhttp = new XMLHttpRequest();
function someFunction()
{
path = "path to another html file";
div = "the name of the div tag's content you want to change eg. content";
AJAX(path, div);
}
function AJAX(path, div)
{
xmlhttp.open("GET", path, false);
xmlhttp.send();
if (xmlhttp.readyState == 4)
{
document.getElementById(div).innerHTML = xmlhttp.responseText;
}
}
now just include the image in the html file.
ajax allows you to change just the content of the div you gave it, without reloading the whole page.
I would try putting your images into photoshop and making the resolution 72 or less. Also if you save the images as a GIFs they should be much smaller.
maybe handle the image loading in an outside script that runs faster than a web page refreshes, then embed it? like a "videoloader.js" so that it can load separately and not have to wait on the html page to load.
<script src="videoloader.js"></script>
you could also convert the images shown on the fly into lesser quality jpgs using javascript
see if this helps:
Load lower quality image if higher one inst available

HTML5 Canvas rendering oddly

I'm in the process of learning HTML5 (and OO Javascript) and am trying to make a simple game engine but rendering to canvas works under very odd conditions. Here is a link to the page and here is my index.html:
<html>
<head>
<script type="text/javascript">
function load()
{
var game = new Game();
game.start();
}
</script>
<title>Game</title>
<style>
canvas
{
outline:0;
border:1px solid #000;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body onload="load()">
<canvas id='c'></canvas>
<script src="classes/Tuple.js"></script>
<script src="classes/Rect.js"></script>
<script src="classes/Sprite.js"></script>
<script src="classes/Game.js"></script>
</body>
</html>
When first loaded, it will give an NS_ERROR_DOM_TYPE_MISMATCH_ERR Exception in Firefox 11.0 and a TypeError Exception in Chrome 18.0. To make it work:
Firefox 11.0
select the URL in the address bar and manually hit enter OR
click the refresh button OR
press F5.
Chrome 18.0
select the URL in the address bar and manually hit enter OR
click the refresh button OR
press F5 OR
press Shift/Ctrl + F5.
What I suspect - Just a guess but it seems like one or more of the .js files is not available/ready by the time it is called during the first page load. Having stepped through it a couple of times in Firebug it seems that the sprite images never get loaded on the first page request.
Perhaps some of the .js files are still being downloaded as the instantiation to Game() is being made, then cached, and are only all available by the second page load?
Any ideas? I'd be grateful for your take on it, thanks!
I copied your files locally and did some testing. It looks to me like it's not your JavaScript files that are unavailable, but your sprite.
You're not loading the PNG until you call Game.start. When you do:
roadSpritesheetImage.src = "assets/sprites/player/playerSpriteSheet.png";
This begins an asynchronous download of the image. The rest of the code is executed before the image has fully loaded, so when you're slicing the image, you're slicing it as if the src attribute were null.
This is why you're able to hit refresh and everything works as expected... the image is cached.
You can sort of preempt the loading of your sprite by adding an image tag just before the canvas:
<img src="assets/sprites/player/playerSpriteSheet.png" style="display:none;" />
This would work because the body load event isn't fired until content (including images) is fully loaded (I believe, I'd have to look this up). Then, if you assign this image to img.src, you will be referencing the cached image.
Alternatively, you could bind the rest of the game functionality to img.onload. For example:
self.loadSprites = function()
{
var roadSpritesheetImage = new Image();
roadSpritesheetImage.onload = function() {
self.entities.push(new Sprite("testTile",
roadSpritesheetImage,
new Tuple(16, 16),
new Rect(0, 0, 32, 16)));
self.run();
};
roadSpritesheetImage.src = "assets/sprites/player/playerSpriteSheet.png";
};
self.run = function() {
var drawSuccessful = false;
drawSuccessful = self.entities[0].draw(self.context);
self.entities[0].nextFrame();
//if we managed to draw the Sprite successfully without any raised exceptions
if(drawSuccessful) {
setTimeout(self.run, 300);
} else { alert("stopping execution of the game."); }
};
self.start = function()
{
self.loadSprites();
};
Doing this is a bit cleaner and it would guarantee you don't have any race conditions with your resources.
I had a similar issue with a jQuery plugin I created to draw an N-puzzle from a source image. I found this MDN documentation extremely useful at the time, although I ended up using sliced divs instead of a canvas.

Categories