How to preload a webpage before showing it? - javascript

I have created a simple webpage with several images, but when a user visits it, the browser loads the images one at a time, instead of all at once.
I want instead to first show a "loading" gif in the center of the page and then, when all the images are downloaded, show the entire webpage to the user at once..
How can I do this?

You can show a loader image by putting it somewhere im <img> tag and use below js code to hide it later on when all images are shown:
window.onload = function(){
var el = document.getElementById('elementID');
el.style.display = 'none';
};
Where elementID is supposed to be the id of loader element/tag.
The load event fires when all images/frames/external resources are loaded, so by the time that event fires, all images are loaded and we therefore hide the loading message/image here.

Edit: I defer to Keltex's answer. It's a much better solution. I'll leave mine here for posterity (unless I should delete the content and my answer entirely? I'm new here).
Another solution, which was used fairly frequently in the past, is to create a landing page that preloads all of your images. When the preloading is done, it redirects to the actual site. In order for this to work, you'd need to get the URLs to all of the images you want to load, and then do something like this:
# on index.html, our preloader
<script type='text/javascript'>
// add all of your image paths to this array
var images = [
'/images/image1.png',
'/images/image2.png',
'/images/image3.png'
];
for(var i in images) {
var img = images[i];
var e = document.createElement('img');
// this will trigger your browser loading the image (and caching it)
e.src = img;
}
// once we get here, we are pretty much done, so redirect to the actual page
window.location = '/home.html';
</script>
<body>
<h1>Loading....</h1>
<img src="loading.gif"/>
</body>

You can do this with JQuery. Say your page looks like this:
<body>
<div id='loader'>Loader graphic here</div>
<div id='pagecontent' style='display:none'>Rest of page content here</div>
</body>
You can have a JQuery function to show pagecontent when the entire page is loaded:
$(document).ready(function() {
$(window).load(function() {
$('#loader').hide();
$('#pagecontent').show();
});
});

HTML
<div id="preloader">
<div id="loading-animation"> </div>
</div>
JAVASCRIPT
<script type="text/javascript">
/* ======== Preloader ======== */
$(window).load(function() {
var preloaderDelay = 350,
preloaderFadeOutTime = 800;
function hidePreloader() {
var loadingAnimation = $('#loading-animation'),
preloader = $('#preloader');
loadingAnimation.fadeOut();
preloader.delay(preloaderDelay).fadeOut(preloaderFadeOutTime);
}
hidePreloader();
});
</script>
CSS
#preloader {
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 9999;
position: fixed;
background-color: #fff;
}
#loading-animation {
top: 50%;
left: 50%;
width: 200px;
height: 200px;
position: absolute;
margin: -100px 0 0 -100px;
background: url('loading-animation.gif') center center no-repeat;
}

Create a div with class name preloader and put a loader inside that div.
style the class preloader just like below
.preloader {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
background-color: white;
/* background-color is would hide the data before loading
text-align: center;
}
Html
<div class="preloader">
Any loader image
</div>
Jquery
$(window).load(function(){
$('.preloader').fadeOut(); // set duration in brackets
});
A simple page loader is ready....

Related

Click on link to show page loader, then make page loader disappear after a defined time, the show destination's url

I'm quite new concerning javascript and I have a problem that seems too simple but it's giving me trouble.
I have a link and I want to achieve that when I click on the link, an invisible page loader appears, then I want the page loader to disappear after a determined amount of time, and finally that it goes to the url of the link.
It's important that it happens on the page before, I don't want the div to be shown onload.
I've tried several extra scripts "setTimeout", "prevent" to hide the loader after a while but it doesn't work... it simply disappears as soon as the page finishes loading.
This is so far the cleanest point I've come to.
<a class="#" href="#" onclick="javascript:document.getElementById('page-loader').style.display='block';"></a>
#page-loader {
position: absolute;
top: 0;
bottom: 0%;
left: 0;
right: 0%;
z-index: 10000;
display: none;
text-align: center;
width: 100%;
padding-top: 250px;
background-color: black;
}
I hope you can help me out with this
You're pretty much on track! When you click a link, you'll need to show the loader div. You've got the CSS defined, and just need to modify the display value to show it (either through style.display or applying another class which overrides the display: none).
Using setTimeout, you can then define a callback to hide the div and navigate.
Here's an example (hides loader after a second, and then navigates after a half second):
// Bind our our click event listener
document.querySelector('a').addEventListener('click', function (e) {
// Calling preventDefault will prevent the browser from navigating (prevents the default behavior)
e.preventDefault();
// Our defined link, where we want to navigate to
const destination = this.getAttribute('href');
// Our loader div - we'll set to a const to reference later
const loader = document.querySelector('#page-loader');
// On click, we immediately want to show our loading div.
// For this demo, we'll use style.display to override our CSS
loader.style.display = 'block';
// Set Timeout - We've defined a 1 second delay
setTimeout(function () {
// After 1 second, we want to hide the loader. Again, using style, we set to 'none'
loader.style.display = 'none';
// One additional set timeout - this allows the browser time to hide the loader. I've defined a half second
setTimeout(function () {
// This will set the URL to our href
window.location.href = destination;
}, 500);
}, 1000);
})
#page-loader {
position: absolute;
top: 0;
bottom: 0%;
left: 0;
right: 0%;
z-index: 10000;
display: none;
text-align: center;
width: 100%;
padding-top: 250px;
background-color: black;
}
<div id="page-loader">Loading</div>
Google
One suggestion: I would avoid using href="#" as a way to avoid navigating. Call e.preventDefault to prevent the browser from immediately navigating to the destination. That way, if JavaScript is disabled/blocked or broken, the link will still work.
Happy learnings!
Try this
const nav = () => {
var loader = document.getElementById('loader');
loader.style.display='block';
setTimeout(()=>loader.style.display = 'none', 3000);
}
#loader{
display: none;
}
<div id='loader'>Loading...</div>
<a href='#' onClick='nav()'>Change</a>
try this
<script>
document.getElementById("page-loader").addEventListener("click", function(event){
event.preventDefault();
document.getElementById("page-loader").style.display='block';
});
<script>

Preloaded images flash at different rates

I'm calling images from a folder at random and putting them in HTML img tags using PHPs glob function.
I'm then using JS to read the URLs and flip the CSS background image of div#wrapper, 300ms for each image. The images should be preloaded as they have HTML img tags. They are being hidden from the user using the following CSS (which should not stop preloading as "display: none" does):
.visuallyhidden {
position: absolute;
overflow: hidden;
clip: rect(0 0 0 0);
height: 1px; width: 1px;
margin: -1px; padding: 0; border: 0;
}
Nonetheless I'm experiencing the images flashing inconsistently / at different rates. It seems that larger file size images cause this to happen, but the images should be preloaded so I'm not sure why this is occurring.
My JS looks like this:
var slides = [];
$('.slide').each(function(index){
slides.push($(this).attr('id'));
});
var slide = 0;
function changeImage(){
if (slide < 10){
var currentSlide = $("#" + slides[slide]);
$('#wrapper').css('background-image', '');
$('#wrapper').css('background-image', 'url("' + currentSlide.attr('src') + '")');
slide++
} else {
$('#headline').removeClass('visuallyhidden');
$('#wrapper').css('background-image', '');
$('#wrapper').css('background-color', '#ef3308');
}
}
setInterval(changeImage, 300);
The site is http://robertirish.com.
Is there a better way to do this / can anyone explain why it's happening?
I'm going to guess it's a loading issue: either that CSS is interfering with preload or else it's being treated differently because you're loading it into the background of another element rather than using the img that you preloaded. Instead, I would load all the images inside the div, absolute-positioned on top of each other, and then just remove them one by one:
CSS:
#wrapper{
position: relative;
}
#wrapper img{
position: absolute;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
}
HTML:
<div id="wrapper">
<img src="image1.png">
<img src="image2.png">
<!--etc-->
</div>
JS:
$(document).on('ready', function(){
var images = [];
$("img", "#wrapper").each(function(){
images.push(this);
});
var timer = setInterval(function(){
if (images.length)
$(images.pop()).remove();
else
clearInterval(timer);
}, 300);
});

Display loader on load event and remove the loader when background image is loaded

I have two divs.
1 : where background image is loaded
2 : where loader gif is loaded.
what I want is , when there is a window.load() event is called then loader gif should displayed , and when background image is fully loaded , then loader gif should be removed. that's what I want to achieve.
$(window).load(function (){
$('.background_image_div').load(function(){
$('.gif_loader_image').hide();
});
});
// this code is not working.
.background_image_div{
background: url(http://www.banneredge.com/images/portfolio.jpg);
width: 600px;
height: 300px;
margin: 0 auto;
border: thin black solid;
z-index: 900;
}
.gif_loader_image{
position: absolute;
width: 50px;
height: 50px;
background: url(https://media0.giphy.com/media/3oEjI6SIIHBdRxXI40/200_s.gif);
// border: thin red solid;
left: 55%;
bottom: 15%;
z-index: 1001;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gif_loader_image"></div>
<div class="background_image_div">
</div>
Thank you.
instead of $(window).load(function (){ do a $( document ).ready(function() { as,
$( document ).ready(function() {
// Handler for .ready() called.
$('.background_image_div').load(function(){
$('.gif_loader_image').hide();
});
});
EDIT Caveats of the load event when used with images as taken from here, .load API
EDIT 2 try a poller, keep polling and check for the image inside the div using .length > 0. Do some changes to your html,
Keep a div and then an image tag inside it with this structure, <div id="backgroundImageDiv"><img src="whatEverTheURLIs" id="backgroundImageID"></div>
Inside your poller check if $("#backgroundImageDiv > #backgroundImageID").length() > 0
If the condition satisfies, hide the gif loader using .hide(). Check for the syntaxes please.
By poller I mean an interval timer.
You can do as like this way.
Just see this link
<div class="feature"><div class="loader"><img src="http://www.ajaxload.info/cache/FF/FF/FF/00/00/00/1-0.gif"></div></div>
$(function(){
var bgimage = new Image();
bgimage.src="http://cdn.wonderfulengineering.com/wp-content/uploads/2016/01/nature-wallpapers-10.jpg";
$(bgimage).load(function(){
$(".feature").css("background-image","url("+$(this).attr("src")+")").fadeIn(2000);
$(".loader").hide();
});
});
http://jsfiddle.net/n4d9xxon
You can try like this :
$(document).ready(function (){
$('.gif_loader_image').fadeOut(1000);
});
body{
background: url(http://www.banneredge.com/images/portfolio.jpg);
width: 100%;
height: auto;
}
.gif_loader_image{
position: fixed;
width: 100%;
height: 100%;
left: 0px;
bottom: 0px;
z-index: 1001;
background:rgba(0,0,0,.8);
text-align:center;
}
.gif_loader_image img{
width:30px;
margin-top:40%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gif_loader_image">
<img src="https://media0.giphy.com/media/3oEjI6SIIHBdRxXI40/200_s.gif" alt="Loader..."/>
</div>
<div class="background_image_div"></div>
The main problem is that your $(window).load doesn't even fire
Why
This won't work since the .load() method was fully removed by jQuery 3 and since you are working with the version 3.1.1 it's not a surprise that your code doesn't work. You have to use now the .on() method to achieve the same effect
So
$(window).load(function (){
$('.background_image_div').load(function(){
$('.gif_loader_image').hide();
});
});
would turn into
$(window).on('load', function (){
$('.background_image_div').on('load', function(){
$('.gif_loader_image').hide();
});
});
Notice
Since you have already the $(window).load function at the beginning you don't have to define it again for your background image because this method will only be fired when all images are fully loaded so I think in your case this should also do the job.
jQuery
$(window).on('load', function () {
$('.gif_loader_image').hide();
});

Completely load a link

I am trying to promote an advertiser and when the user clicks on the advertiser link, it redirects 5-6 times through different links (for tracking purposes) before reaching the advertiser's website.
Is it possible to show some kind of loading icon on the page on which the user clicks on the link and then redirect the user to the advertiser's website when the link is completely loaded?
I searched and found this code, but I am not sure how to implement this in my case:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>
//paste this code under the head tag or in a separate js file.
// Wait for window load
$(window).load(function() {
// Animate loader off screen
$(".se-pre-con").fadeOut("slow");;
});
.no-js #loader { display: none; }
.js #loader { display: block; position: absolute; left: 100px; top: 0; }
.se-pre-con {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url(images/loader-64x/Preloader_2.gif) center no-repeat #fff;
}
<div class="se-pre-con"></div>
Since it redirects to someone elses website, you cannot change the content of those websites to have a loading icon.
You could load it in an iframe and when the iframe has not changed its location in, say, 5 seconds, show the iframe as the whole page and hide the loading icon. You can also set the target to '_top' so it changes the url in the browser whenever you click on a link.
Click!
<iframe id="preload-frame" style="position: absolute; z-index: 9999; top: 0; left: 0; bottom: 0; right: 0;" hidden>
<script type="text/javascript">var iframe=false;</script>
</iframe>
<div class="se-pre-con" hidden></div>
var frame = document.getElementById('preload-frame');
onclickConstructor = function (href) {
return function() {
document.getElementsByClassName('se-pre-con')[0].removeAttribute('hidden');
var timer;
var cleanup = function() {
frame.removeAttribute('hidden');
frame.setAttribute('target', '_top');
document.getElementsByClassName('se-pre-con')[0].setAttribute('hidden', 'true');
}
frame.onload = function() { // Whenever the iframe (re)loads the whole page
if (timer) {
(clearTimeout || clearInterval)(timer);
}
timer = setTimeout(cleanup);
}
frame.src = href;
};
}
if (iframe !== false) {
var trackingLinks = document.getElementsByClassName('tracking'), function(el);
for (var i = 0; i < trackingLinks.length; i++) {
el.onclick = onclickConstructor(el.href);
el.href = 'javascript:void(0);';
};
}

Onload function runs before loading of all elements

I have a div on my page which I want to show after all elements (scripts, pictures and so on) finish loading. But it seems that the onload function doesn't work as I can see the page before everything is loaded. I have only one js file linked to my page, and below I showed how I organized the code (hope its a right way). I have also put a broken img link to the page, to test if the function executes without the missing file, and it does.
HTML
<div id="dvLoading"></div>
CSS
#dvLoading{
position: fixed;
height: 100%;
width: 100%;
top: 0;
background: red;
z-index:9999;
}
JQuery
var onLoad = function(){
$(window).load(function(){
$('#dvLoading').fadeOut(500);
});
}
var someFunction1 = function(){
//some function
}
var someFunction3 = function(){
//some function
}
var someFunction3 = function(){
//some function
}
$(document).ready(function(){
onLoad();
someFunction1();
someFunction2();
someFunction3();
});
Try this instead :
$( window ).load(function() {
$('#dvLoading').show().delay(3000).queue(function(n) {
$(this).fadeOut("slow").delay(1000); n();
});
});
CSS
#dvLoading{
display: none;
position: absolute;
height: 100%;
width: 100%;
top: 0;
background: red;
z-index:9999;
}
Your issue could be that you're trying to call a function which fires onload within a document.ready wrapper.
EDIT
This will show the hidden div and delay the fadeout for however long you need once all resources have loaded.
EXAMPLE
JS FIDDLE

Categories

Resources