I'm building a page to display a bunch of webcam images and update them periodically so that the page can be used for at-a-glance monitoring. However, I'm having issues getting the periodic reload working. My code looks something like:
<div class='cameras'>
<div class='camera'>
<h4>Desk</h4>
<img height='240' src='http://somehost/cameras/cam0/lastsnap.jpg' width='320'>
</div>
<div class='camera'>
<h4>Main Room</h4>
<img height='240' src='http://somehost/cameras/cam1/lastsnap.jpg' width='320'>
</div>
<div class='camera'>
<h4>Studio</h4>
<img height='240' src='http://somehost/cameras/cam2/lastsnap.jpg' width='320'>
</div>
</div>
Ideally I'd like to get these things reloading every couple of seconds from their specified URLs without having to generate individual JS for each camera. I've got jQuery in use for a few other bits and pieces, so sticking to that would be great - then again, a plain JS solution is fine too.
Any ideas, StackOverflow JS Gods?
Okay, solved this:
function refreshCameras() {
$('.camera img').attr('src', function(i, old) { return old.replace(/\?.+/,"?i=" + (Math.random()*1000)); });
setTimeout(refreshCameras, 1000);
}
function refreshCamerasFirst() {
$('.camera img').attr('src', function(i, old) { return old + "?i=" + (Math.random()*1000); });
setTimeout(refreshCameras, 1000);
}
$(function() {
setTimeout(refreshCamerasFirst, 1000);
});
Will take all img elements in a "camera" class, and refresh them every second with cache-busting via a random number added to the URL, which is changed every reload without making the URL obscenely long using a regexp to replace the existing number.
Generate image sources to the images [for regular intervals of time]
var img = []; //just an image source. you can write your own code for image source
img[0] ='http://site.com/pics/pic.jpg';
img[1] ='http://site.com/pics/pic1.jpg';
img[2] ='http://site.com/pics/pic2.jpg';
img[3] ='http://site.com/pics/pic3.jpg';
$(function() {
$.each(img, function(i, val) {
var images = new Image();
images.src = val; //preloading images for my example purpose
});
function reload() {
$('img.alter').each(function() { //generate a url for image source.
var src = img[Math.floor(Math.random() * img.length)];
$(this).attr('src',src);
});
}
setInterval(reload , 5000)
});
Test it here
PS :this technique doesn't require the reloading of entire page
Try rewriting meta tag on you page as
<meta http-equiv="Refresh" content="2; URL=yourpage.php">
It works cool with the text.Checkout with images
If you want to refresh the page in a specified duration you can do that in html also
Add this tag to your page head tag
<meta http-equiv="refresh" content="1">
here content is the duration in seconds
Refer this
http://webdesign.about.com/od/metataglibraries/a/aa080300a.htm
Related
I don't like lazy-loading because it looks quite ugly for the user in terms of UX. However, I understand the benefits (faster page load, low bandwidth, high PageSpeed scores etc.)
I am planning to write a javascript code which will:
Stay in the bottom > Wait for the page to fully load > After 3 seconds it will work > Force load all the images which were lazy-loaded previously during initial page load
With this, I won't lose any speed scores (because it will load as normal with lazy loaded images) But, also will load the full images when everything is done, so user won't notice. (we do the same for loading live chat scripts. It works pretty nice)
It will probably look something like this:
<script>
window.onload = function() {
setTimeout(function(){
var ForceLoadImages = document.createElement('script');
ForceLoadImages.type = 'text/javascript';
ForceLoadImages.src = 'link-to-the-script-to-force-load-images.js';
document.body.appendChild(chatScript);
}, 3000);
};
</script>
I am not a js expert. This was just a dummy example to give an idea. I am specifically asking how to write the content of that "link-to-the-script-to-force-load-images.js" part. Will appreciate any inputs.
There was a similar question here, but need an answer for Wordpress.
I guess that the wp lazy load uses data-src attribute to hold the image and when in view port, its adding the image to the src attribute.
Simplified like this:
<img data-src="URL"/>
*if its not like this, find in your source code the attribute where image is hold when out of view
What you need to do is select all images and change the data-src to src like this:
var images = document.querySelectorAll('img');
window.onload = function() {
setTimeout(function(){
for (var i=0; i<images.length; i++) {
if(images[i].getAttribute('data-src')) {
images[i].setAttribute('src',images[i].getAttribute('data-src'));
images[i].removeAttribute('data-src'); // optional if you need to remove data-src attribute after setting src
}
}
}, 3000);
};
<div class="container">
<img data-src='https://picsum.photos/id/237/200/300' />
<img data-src='https://picsum.photos/seed/picsum/200/300' />
<img data-src='https://picsum.photos/200/300' />
</div>
I just wanted to put the solution as an answer (thanks to kaize) who are looking for something like this. It is very clean and works nice:
<script>
var loadimages = document.querySelectorAll('img');
window.onload = function() {
setTimeout(function(){
//Force Load images
for (var i=0; i<loadimages.length; i++) {
if(loadimages[i].getAttribute('loading')) {
loadimages[i].removeAttribute('loading');
}
}
}, 3000);
};
</script>
Who is this for?
For those who does not like the user-experience of lazy loading images. But applying it due to PageSpeed scores.
Where to place this?
Place this to the bottom of your page.
What does this script do?
This script runs 3 seconds after the page loaded completely. It force-loads all the images which were waiting to get into the viewport to be lazy-loaded by removing the "loading" attribute. So that, you get good pagespeed scores for deferring image loads meanwhile keeping the user experience better. (Keep in mind that you lose the bandwidth advantage of lazy-loading concept)
I'm talking about an icon that is displayed on a tab during page loading.
Chrome:
Firefox (with TreeTab plugin):
You get the idea. I want to make it seem like the page is loading, when it's already loaded. Some event fires is javascript and then the tab looks like it's being loaded. Is there a way to do that?
One way I can think of is to replace a favicon with a spinner, but I'm not sure if it's possible to change on the fly and even if it is, it would be a hassle to make it cross-browser.
I don't think it is a good idea to do it, you'll make your users do a lot of useless requests, and this kills trees : /
IMO, it's better to do all you have in the page itself, and let the browser's UI do his own stuff.
But since I liked the challenge, here is one hacky way :
Loading an iframe will trigger this icon in both chrome and Firefox[1], so you could ,
append an iframe in the document,
set its src to some huge document,
onload of the iframe, set it again with a ? cache hack,
regularly check if the duration has elapsed so you can remove the iframe's src.
[1] It seems that Firefox does trigger the icon only if it was triggered when the document was still loading.
In code :
// how to use :
showTabLoader(25000);
// takes duration in ms as only parameter
function showTabLoader(duration) {
if (!duration) return;
var now = performance.now();
// To avoid flickering, you need some big document
// Please change this url in your script, wikimedia may not be happy with us.
var url = 'https://upload.wikimedia.org/wikipedia/commons/3/35/Viborg_Katedralskole_Symmetrical.jpg';
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.onload = function() {
if (performance.now() - now < +duration) {
this.src = url + '?' + Math.random();
}
};
var check = function(time) {
if (time - now > +duration) {
iframe.src = '';
iframe.parentNode.removeChild(iframe);
return;
}
requestAnimationFrame(check);
}
requestAnimationFrame(check);
iframe.src = url;
}
I recently thought of the same idea. A neat option is to use a dynamic favicon instead of hacking in hidden requests, which is a really bad idea in my opinion. I found this example. It's to much code to include here and doesn't work in iframes so no way of showing it directly on Stackoverflow. Instead i describe the idea behind.
https://www.cssscript.com/favicon-loading-indicator-favloader/
The idea is simple. Replace the favicon in an interval with the loading animation icons. A favicon cannot be GIF so you have to load each image step by step with JS. When you are done, simply replace it back with the original favicon.
For me this works at least in all chrome based browsers. Firefox throw some errors in this example, but i guess it can be fixed.
Alternitive:
There is no function that shows the actual loading process of the webpage. But you can do it manually, like you said!
The event below starts to run when the page is fully loaded, even after all the images are loaded:
$(window).on('load', function() {
// do stuff
});
So what you could do is set up your html like this:
<div class="preloader">
// your loader here, animations, video, gif, anything you want
</div>
<div class="main" style="display: none;">
// the page
</div>
and your jquery like this:
$(window).on('load', function() {
setTimeout(function() {
$('.preloader').css('display', 'none');
$('.main').css('opacity', '1');
}, 5000); // <-- 5seconds
});
And there you have your manual loading function! Works perfect.
Example website: ifly50
EDIT:
added code snippet
Code snippet:
$(window).on('load', function() {
setTimeout(function() {
$('.preloader').css('display', 'none');
$('.main').css('display', 'block');
}, 3000); // <-- 3 seconds
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="preloader">loading</div>
<div class="main" style="display: none;">main</div>
previosly my client hadan swf for their logo, this doesn't show well needless to say. i have made a single loop gif for the customer's animated logo. i want it to play once per page load. it currently plays once ever(if at all)
the web page is on a .net server, so i can't implement php code.
i tried a javascript cachebuster:
<img id="gif_animata" src="images/fca-1.gif" width="550" height="50">
<script type="text/javascript">
var gifSource = $('#gif_animata').attr('src'); //get the source in the var
$('#gif_animata').attr('src', ""); //erase the source
$('#gif_animata').attr('src', gifSource+"?"+new Date().getTime()); //add the date to the source of the image... :-)
</script>
...i would comment on the question sourced, but i can't comment yet
anyway, it didn't do anything for me. the image name still shows as "fca-1.gif" no change to the name when i load the page, and i can see the javascript when inspecting the source
try simply this code
setTimeout(function() {
setInterval(function() {
$('#gif_animata').attr('src',$('#gif_animata').attr('src'))
},1)
}, 2000)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<img id="gif_animata" src="http://www.lmpenterprises.co.uk/ekmps/shops/pearl/resources/image/animated-gif-2-f.gif" />
this code after 2 seconds set every 1 millisecond the source so it is always the first frame
I have a very complex page with a lot of scripts and a rather long loading time. On top of that page I want to implement the jquery Nivo Slider (http://nivo.dev7studios.com/).
In the documentation it says I have to list all images for the slider inside of a div#slider
<div id="slider">
<img src="images/slide1.jpg" alt="" />
<img src="images/slide2.jpg" alt="" title="#htmlcaption" />
<img src="images/slide3.jpg" alt="" title="This is an example of a caption" />
<img src="images/slide4.jpg" alt="" />
</div>
However I might have 10 images with a 1000x400px which is quite big. Those images would load when the page loads. Since they are in my header this might take quite a while.
I looking for a way to use any jquery Slider Plugin (like the nivo slider) but either dynamically load images or load all those images after everything else on my page has loaded.
Any idea how I could solve that?
Is there even a way to start a javascript process after everything else on the page has loaded? If there is a way I might have an solution for my problem (using the jquery ajax load() method) ... However I have no idea how to wait for everything else to load and then start the slider with all the images.
Here's what we did and its working great. We skipped setting src attribute of img and added img-location to a fake attribute lsrc. Then we load a dynamic image with lsrc value, and set the src of actual image only after its loaded.
Its not about faster loading, but its about showing the images only when its downloaded completely on your page, so that user do not have to see that annoying half-loaded images. A placeholder-image can be used while the actual images are being loaded.
Here's the code.
$(function(){
$.each(document.images, function(){
var this_image = this;
var src = $(this_image).attr('src') || '' ;
if(!src.length > 0){
//this_image.src = options.loading; // show loading
var lsrc = $(this_image).attr('lsrc') || '' ;
if(lsrc.length > 0){
var img = new Image();
img.src = lsrc;
$(img).load(function() {
this_image.src = this.src;
});
}
}
});
});
Edit: Trick is to set the src attribute only when that source is loaded in temporary img. $(img).load(fn); handles that.
In addition to Xhalent's answer, use the .append() function in jQuery to add them to the DOM:
Your HTML would just have:
<div id="slider">
</div>
And then your jquery would be:
jQuery(function(){
$("#slider").append('<img src="images/slide1.jpg" alt="" />');
});
check out jquery load() event, it waits for everything including graphics
$(window).load(function () {
// run code
});
on load you could then load the images using:
var image = new Image();
image.src = "/path/to/huge/file.jpg";
You can add a function onload to the image too
image.onload = function() {
...
}
I am using the below to power my slider and improve the page load performance.
for (var i = document.images.length - 1; i >= 0; i--) {
var this_image = document.images[i];
var src = $(this_image).attr('src') || '' ;
if(!src.length > 0){
var lsrc = $(this_image).attr('lsrc') || '' ;
if(lsrc.length > 0){
$(this_image).attr("src",lsrc);
}
}
}
the best way to use is b -lazy js.
bLazy is a lightweight lazy loading image script (less than 1.2KB minified and gzipped). It lets you lazy load and multi-serve your images so you can save bandwidth and server requests. The user will have faster load times and save data loaded if he/she doesn't browse the whole page.
For a full list of options, functions and examples go to the blog post: http://dinbror.dk/blog/blazy.
The following example is a lazy loading multi-serving responsive images example with a image callback :) If your device width is smaller than 420 px it'll serve a lighter and smaller version of the image. When an image has loaded it removes the loader in the callback.
In Html
<img class="b-lazy"
src="placeholder-image.jpg"
data-src="image.jpg"
data-src-small="small-image.jpg"
alt="Image description" />
In js
var bLazy = new Blazy({
breakpoints: [{
width: 420 // Max-width
, src: 'data-src-small'
}]
, success: function(element){
setTimeout(function(){
// We want to remove the loader gif now.
// First we find the parent container
// then we remove the "loading" class which holds the loader image
var parent = element.parentNode;
parent.className = parent.className.replace(/\bloading\b/,'');
}, 200);
}
});
Example
jquery has a syntax for executing javascript after document has loaded:
<script type="text/javascript">
jQuery(function(){
//your function implementation here...
});
</script>
I have an HTML page where I want to refresh a lot of images every 30 seconds after the HTML page has been downloaded. I understand how to do this with Jquery and a single image, but I want to use about 200 custom urls to determine the current image to display for over 200 images. I need to find an efficient way to have jquery call the custom url associated with each image to download the url for the needed image as it changes, and then update the image in the page when it changes.
Current hyperlink example to demonstrate the custom urls.
link to url for image
Each custom url will return an image tag like this (or any other text that makes this simpler for jquery)
<img src="/static/someImage.jpg">
What is the simplest way to have jquery call the custom url for each image to download the image url, image html, or some other text that jquery can use to download the right image every 30 seconds? Please keep in mind that I will have about 200 of these on a page.
Create a helper on the server side that returns all URLs at once. You can then lookup each image in the returned object (I'd recommend using JSON for this).
You can loop the images
$(document).ready(function(){
setTimeout(function(){
$('img .reloadable').each(function(){
orginal = $(this).attr('src');
if(original.indexOf('?') == -1)
{
original = original + '?' + Math.random();
}else if(original.indexOf('&') == -1)
{
original = original + '&t=' + Math.random();
}
$(this).attr('src',original);
})
},30000) // 30 seconds
})
Using the random with create a new uri as its different to the previous one, so the dom will reload it as its not currently cached !
One way is to create a DIV for each link and make the url to call the DIV id. Then if you make each DIV part of the same class, you can then iterate through the DIVs of that class and call each url.
<div id='true.txt' class='isSolvedImage'>
<img src="_images/solved.png">
</div>
<div id='false.txt' class='isSolvedImage'>
<img src="_images/solved.png">
</div>
<script src="jquery-1.4.2.min.js" type="text/javascript"> </script>
<script type="text/javascript">
$('img').hide();
function updateImages() {
var getDivs = 0;
//iterate div with class isSolvedImage
$("div.isSolvedImage").each(function() {
var img = $(this).find('img');
// send ajax requrest
$.get(this.id, function(data) {
if(data == 1){
img.show();
}
else{
img.hide();
}
});
});
}
setInterval("updateImages()", 30000);
</script>
The simplest thing to do would just be to use a full page refresh:
<meta http-equiv="refresh" content="60" />
You can use the same code to refresh individual elements, just by specifying the id.
This is probably the easiest solution to have it update on the front end of the page.