Javascript : Preload loading image - javascript

I'm having trouble when displaying my loader in Javascript. Indeed, I have a lot of heavy videos in my assets folders, and when I load my page in Javascript, my image loader is showing only after a few seconds, whereas i would like it to be loaded first.
Is there a way to preload it, before all my video assets ?
Thanks a lot by advance !

In a script that gets run before any of the videos start downloading, etc.:
var img = new Image();
img.src = 'http://yoursite.com/preload-this-image.gif';
This should ensure that the image displays as soon as the DOM renderer reaches it.
If there are any heavy assets before it in the DOM holding back that process, you can move them ahead and move them back after document load with JavaScript.

You can show a loader gif before the whole page renders:
CSS:
.loader {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 9999;
background: url('/img/page-loader.gif') 50% 50% no-repeat rgb(249,249,249);
}
HTML:
<div class="loader"></div>
JS:
$(window).load(function() {
$('.loader').fadeOut('slow');
});

You can actually convert the image into a base-64-encoded string, and include it in your CSS or HTML. This guarantees that it'll be loaded before anything else.
Here's an image converter: http://webcodertools.com/imagetobase64converter
And you can use it as an inline image, or CSS background image:
Inline HTML:
<img alt="" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH+GkNyZWF0ZWQgd2l0aCBhamF4bG9hZC5pbmZvACH5BAAKAAAAIf8LTkVUU0NBUEUyLjADAQAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQACgABACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkEAAoAAgAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkEAAoAAwAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkEA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lQGBMLAJibufbSlKAAAh+QQACgAGACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAAKAAcALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==);

I would hard code image in the source of the page as base-64-encoded string, or replaced with an inline svg.
Also you could use rel="preload" and see if this works out for you:
<link rel="preload" href="bg-image.png" as="image" media="(max-width: 800px)">
see this: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content

Related

Wait for specific image resource to be downloaded/loaded and not execute any following javascript code until the resource of the image is loaded?

I have some <img> tags and some <div> tags with 'background: url('example.jpg');
And I want to wait until these images are downloaded and not execute any following javascript code ultil these images are downloaded and loaded. So only after I can call a function to deactivate my website loader and keep adding the other scripts for animating and stuff...
PS: I don't want to wait ultil all images are loaded cause that will take too long, i just want some images (like the first background) to be loaded before I deactivate my website loader...
You could load it into memory first then apply it to the element
var img = new Image();
img.onload = function() {
console.log('image loaded');
document.querySelector('div.bg').style.backgroundImage = `url(${img.src})`
}
img.src = "https://picsum.photos/200/300?" + new Date().getTime();
div.bg {
height: 500px;
width: 600px;
background: #000;
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
<div class='bg'></div>
Javascript-beginner here, so I don't know if there are any existing functions or anything that might take care of this for you.
My search-results came empty-handed to your specific question, so this is what I would do if I was sure there is nothing out there:
periodically check whether a number of images already have a size.
Should be easy enough to build a dynamic list, or to specify a few specific images you want to load, I guess.

Responsive blank image overlay for an image

I'm trying to find a javascript solution where it dynamically overlay a blank image similar to David Walsh's dwImageProtector Plugin (http://davidwalsh.name/image-protector-plugin-for-jquery). My problem with that plugin is, first, it append the overlay to the 'body' which actually don't align to the targeted image and second, that plugin is not built for responsive, meaning if I adjust the width of my browser the overlay image will stay the same way as the original parsed image size.
my code look something like this:
//css
.column { position: relative }
.column img { width: 100%; }
// html
<div class='column'>
<img class='protect' src='img/source.jpg' />
<span>copyright 2013</span>
</div>
Note: The overlay trick only deters at best the uninitiated visitors who want to steal your images. There is no feasible way of detering thefts because:
Visitors can check the image source from Inspector, and download it directly (but you can circumvent that using .htaccess rules that prevents direct file access)
Visitors can hide the image overlay
Visitors can take a screenshot of the page
Visitors can sniff files that are served from the server to their browser
Back to my solution: You don't actually need to use JavaScript (or jQuery) for this purpose. A simple CSS trick using pseudo-elements will work. Let's say you have the following markup:
<div class='column'>
<div class='protect'>
<img src='img/source.jpg' />
</div>
<span>copyright 2013</span>
</div>
Your CSS:
.protect {
position: relative;
}
.protect:after {
background-image: url(/path/to/overlay);
background-size: cover;
content: "";
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: 10;
}
If you can't change the markup, though, then you should rely on using jQuery to wrap your image element with a <div class="protect"> element, and apply the same styles as mentioned above, i.e.
$("img").each(function() {
$(this).wrap('<div class="protect" />');
});

$.height returns 0 on first load of page

I'm having the following img on the page
<img class="some-class" src="img/some-img.gif" style="top: 29px; left: 121px;">
In css I have
img.some-class {
display: inline-block;
position: absolute;
}
img is located in div having display: inline-block.
When I'm doing console.log($img.height()) it outputs 0 on first load of page (i.e. on first load after opening of browser). Still after I refresh page console.log($img.height()) outputs real value of height of img. What can be a reason of problem?
UPD. please note that an img is added dynamicaly.
Before the image is loaded, the browser doesn't know the height. When you load the page the second time, the image is already in the browser cache, so it knows the height.
You must place your console.log() call inside a $(window).load() block. This will run after the images have loaded.
$(window).load(function() {
console.log($('img#myimg').height();
});
If the image is added dynamically, then you can put a load() handler on the image itself:
$('img#myimg').load(function() {
console.log($(this).height());
});
Load event info:
http://api.jquery.com/load-event/
More info found on Google:
http://web.enavu.com/daily-tip/daily-tip-difference-between-document-ready-and-window-load-in-jquery/

jQuery loader for the intro

My Site have a small introduction with heavy images, here is the little animation on it:
Jquery
$(function(){
$('#intro-left').stop().delay(5000).animate({'width':'0'},4000, 'easeOutQuint');
$('#intro-right').stop().delay(5000).animate({'width':'0','left':'100%'},4000, 'easeOutQuint');
$('#intro-rights').stop().delay(5000).animate({'width':'0','left':'100%'},4000, 'easeOutQuint');
$('#intro-logo').stop().delay(10000).fadeOut(1500);
});
HTML
<div id="intro-left"></div>
<div id="intro-right"></div>
<div id="intro-rights"></div>
<div id="intro-logo"><img class="top" src="images/intro_top.jpg"><img class="logo" src="images/intro-logo.jpg"><img class="bot" src="images/intro-bot.jpg"></div>
<div id="header">
Rest of the Site...
CSS
#intro-left {
position: absolute;
z-index: 10000;
top: 0;
left: 0;
background: url(images/intro-left.png) right no-repeat;
width: 58%;
height: 100%;
}
#intro-right {
position: absolute;
z-index: 9000;
top: 0;
left: 32%;
background: url(images/intro-right.png) left no-repeat;
width: 68%;
height: 100%;
}
and as you can see, it is just full screen images and colors, the problem is that the Web surfer may miss that intro, or, have it introduced in a bad way, with images loading...
It make the intro ugly, then,
i want to know if there is a way to make all the content in the page invisible while it is loading, then, when all the content of that page is loaded, make it visible.
Maybe a display: none during the loading and then the page is loading make it block, something like that would work,
Is that posible? Or similar to it?
Thanks a lot in advance!
The following link will take you to a jquery loading plugin that allows you to add a pre-loader to your website which should be a great solution to your problem.
http://www.gayadesign.com/diy/queryloader2-preload-your-images-with-ease/
You would use the onComplete() function to have your intro start going after the page / pre-loader is finished.
Might look something like this:
$("body").queryLoader2({
barColor: "#6e6d73",
backgroundColor: "#fff1b0",
percentage: true,
barHeight: 30,
completeAnimation: "grow",
onComplete: function(){
$('#intro-left').stop().delay(5000).animate({'width':'0'},4000, 'easeOutQuint');
$('#intro-right').stop().delay(5000).animate({'width':'0','left':'100%'},4000, 'easeOutQuint');
$('#intro-rights').stop().delay(5000).animate({'width':'0','left':'100%'},4000, 'easeOutQuint');
$('#intro-logo').stop().delay(10000).fadeOut(1500);
}
});
Try encasing the whole page contents in <div id='loadHide' style='display:none'>...</div>
You can then add
$('#loadHide').show();
To the beginning of your code block, to display the contents once the document has finished loading.
The finished javascript would be:
$(function(){
$('#loadHide').show();
$('#intro-left').stop().delay(5000).animate({'width':'0'},4000, 'easeOutQuint');
$('#intro-right').stop().delay(5000).animate({'width':'0','left':'100%'},4000, 'easeOutQuint');
$('#intro-rights').stop().delay(5000).animate({'width':'0','left':'100%'},4000, 'easeOutQuint');
$('#intro-logo').stop().delay(10000).fadeOut(1500);
});
The display:none/display:block would likely work, and jQuery has a method of running code only after the page has fully loaded.
$(document).ready(function() {
$('#content').show();
// I would also recommend that you start your animation here, too
});
The $(document).ready solutions are good, but the document can be ready before all of your images are finished loading. If your main concern is waiting until all images are loaded, I would check out this question, which suggests that you use the $(window).load callback. Also, you can add onload event handlers to your images to be sure you don't start animating before images are loaded.
var image = new Image();
image.onload = function() {
//Animation code here
};
image.src = "http://i2.ytimg.com/vi/yW5Vv23HQWM/hqdefault.jpg";
This would only work if you are loading a single image. If you need to wait on more than one image, you would put your animation code somewhere else and each time an onload event was fired, you would check to see if all of your needed images are loaded yet. Once they have all loaded, call your animation code.

How can I show a loading screen while a really large image is loading?

I have a 5MB Image that takes about 2-3 mins to load. While It loads, I want to have a loading screen. That loading screen will disappear after the images loaded. (The image is a sprite image; I use CSS to split it).
If this is possible, then how can I do it? If this isn't possible, then what other ways can I use to hide the loading of the image (or lower the image size)?
That image is a sprite image.
I use css to split them.
Unless there is additional information which hasn't been stated, at 5MB you have defeated any advantages of a CSS sprite. Split it into separate files and lazy load on demand.
If you are using/can use jQuery this plugin does a nice job lazy loading.
Also ensure that you are using the best compression possible. Even if you must use lossless compression, there are still some gains which can be made by removing metadata from the image files.
"Save for Web" in Photoshop is great for balancing lossy compression (quality versus size) and also gives you the option to not embed metadata in image files. You can use a tool like Yahoo SmushIt if you don't have access to Photoshop.
Just hide the page/element behind some loading layer and remove that layer after the images are loaded:
<!-- within you site header -->
<script type="text/javascript">
/* display loader only if JavaScript is enabled, no JS-lib loaded at this point */
document.write('<div id="loader" style="display:table; position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 10000; background: #fff;">'
+ '<div style="display:table-cell; vertical-align:middle; text-align: center;">'
+ 'loading…<br /><img src="icon.load.gif" />'
+ '</div></div>');
</script>
<!-- at the bottom of you HTML (right before closing BODY-tag) -->
<script src="jquery.min.js"></script>
<script type="text/javascript">
/* hide the loading-message */
$(window).load(function(){
$('#loader').fadeOut(500);
});
</script>
The trick is to use $(window).load() as event handler, which does not get fired until all page contents are fully loaded.

Categories

Resources