I'm loading image tags via AJAX and inserting them with the conventional .html(content) function in jQuery alongside a bunch of other HTML. However, this question still applies if you're loading a page from scratch. Now, I have a background image placeholder to be put there while the image loads. I want this background image to go away when the image loads.
Problem:
If I attach a conventional .load(function) event listener, I am concerned that the image might load before the hook is applied (putting the hook in a small JS <script> right after the image instead of in a $(function(){}) block might help a bit). I have yet to encounter such behaviour, but I know of nothing in the specification that prevents this from happening (since the image tag ought to be fully parsed before the hook is applied).
My current solution. Put the command in an inline onload= property within the image tag.
Is there a better way?
Up until a week or so ago I would have been lost too. Thankfully this answer to another question will help you out:
Basically put this in $():
$(function(){
var img = $("#idofimage").load(function () {
/* your magic to swap out placeholder */
});
if (img[0].complete) {
// Trigger the load handler if the image
// is already loaded
img.trigger('load');
}
});
You don't need jQuery for this, you can do it with CSS.
.my-img-loader-class { background:url('placeholder-or-progress'); }
Or if you don't want to change your HTML:
#container img { background:url('placeholder-or-progress'); }
To show placeholders while images are loading in a specific div.
The way it works is the image element will show the placeholder image as its background, and when the src loads it will appear above the placeholder, so as to replace it nicely.
Related
I have a application that loads CSS styles dynamic based on user preference. I use requirejs to load these like:
require(['css!dir/styles'], function(){ .... });
this works great but I don't want to show the screen until all the styles have fully initialized.
I've added a CSS class to the body of the page called hide-page and then remove that class when the callback occurs. Like:
setTimeout(function() { $(document.body).removeClass('hide-page'); }, 100);
but even with the settimeout, the page still loads jumbled until everything has initialized. I was thinking about doing a setInterval and checking if a particular style has been applied to a node like:
setInterval(function(){
if($(document.body).style('background'') === "#FFFFFF"){
$(document.body).removeClass('hide-page');
}
}, 10);
but thats kinda hackey. Is there a better solution anyone has to accomplish this?
You don't say how you're hiding the page content, but that could be the problem if you're using display:none.
Try visibility:hidden instead. This will allow the browser to allocate the space needed to construct the page, so you shouldn't see the jumbled FOUC.
I'm using this lazy load jQuery script ( http://www.appelsiini.net/projects/lazyload ) to lazy load images when they appear in the viewport, but I want to run some javascript / styling to style the new, full image that is loaded.
How can I run javascript once the image has been loaded?
The jQuery Lazy Load plugin has a callback parameter called
appear, that gets triggered for every image, once it's been loaded. Use it like this, in this case e.g. to put a red border on the image, once it's loaded (this in the callback refers the raw DOM img object):
$(document).ready(function () {
$("img").lazyload({
appear: function () {
//Image is loaded. Put javascript here.
this.style = "border: 1px solid red";
}
});
});
Although I will say, if you wanna add styling to the image, you should use css instead. But there might be cases where you actually wanna trigger javascript on image-load, and this seems like the way to do it with the lazy load plugin :)
Bind a handler to the image load event. But be aware that you have to set the handler fore every image, as the load event doesn't bubble up the DOM tree. Here is a way:
$('#img').on('load', function() {
//do some styling...
});
However, my experience tells me that, with this event it's better if you use the onclick attribute. It my happen that, when you set the handler via jQuery, some images have already loaded.
I'm a creating a loading screen for website I am making. The website loads many images, scripts, etc. The HTML and CSS part is great, but I need a way to guarantee that the "loading..." image will be loaded before anything else.
I'm using jQuery, and everything is initiated within $(function () { ... });. I imagine that the code for this would need to be called before/outside that block, and the code to remove the loading screen will be called at the very end of that block. Currently, the loading image is set as a DIV background, which is the way I prefer it. However, if it's completely necessary, I will settle for an IMG tag.
Update: (solution)
I was able to answer my own question by using a combination of Robin and Vlad's responses. Both were very good, and excellent answers, however the problem is that they were aimed to load an image before another image, rather than load an image before anything else. (CSS, JS, etc...)
Here's the dirty version of what I came up with:
var files = [new Image(), document.createElement('link'), document.createElement('script')];
files[0].setAttribute('src', 'images/loading.gif');
files[1].setAttribute('rel', 'stylesheet');
files[1].setAttribute('type', 'text/css');
files[1].setAttribute('href', 'test.css');
files[2].setAttribute('type', 'text/javascript');
files[2].setAttribute('src', 'js/jquery-1.5.1.min.js');
window.onload = function (e) {
document.getElementsByTagName('head')[0].appendChild(files[1]);
document.getElementsByTagName('head')[0].appendChild(files[2]);
}
Taking a look at the load sequence on the network tab of Chrome's developer console shows that 'loading.gif' is loaded first, then 4 dummy images, then 'test.css', and then 'jquery.1.5.1.min.js'. The CSS and JS files don't begin to load, until they've been inserted into the head tag. This is exactly what I want.
I'm predicting that I may begin to have some problems, however, when I begin to load a list of files. Chrome reports that sometimes the JS file is loaded first, but the majority of the time the CSS file is loaded first. This isn't a problem, except when I begin to add files to load, I will need to ensure that jQuery is loaded before a script file that uses jQuery.
If anyone has a solution for this, or a way to detect when the CSS/JS files are finished loading, using this method, then please comment. Though, I'm not sure that it's going to be a problem yet. I may need to ask a new question in the future about this, if I start to run into problems.
Thank you to every who has helped with this issue.
Update: (glitch fix)
I ended up running into a lot of problem with this method, because the script files were being loaded asynchronously. If I would clear the browser cache, and then load the page, it would finish loading my jquery dependent files first. Then if I refreshed the page, it would work, because jquery was loaded from cache. I solved this by setting up an array of files to load, then putting the load script into a function. Then I would step through each array item using this code:
element.onload = function() {
++i; _step();
}
element.onreadystatechange = function() {
if (("loaded" === element.readyState || "complete" === element.readyState)) { ++i; _step(); }
}
You can reuse resource prealoding browser support.
I'm not sure it works across all browsers but in my case this approach helps me to load images first. Also it allows to define concrete images so UI specific could be skipped
First define in header what resource you want to preload and define resource priority
<link rel="preload" href="link-to-image" as="image">
or
<link rel="preload" href="link-to-image">
Second line allow to increase loading priority across all object types (scripts / images / styles). First line - only through images.
Then define in body link to image as usual:
<img src="link-to-image" alt="">
Here is my working example
https://jsfiddle.net/vadimb/05scfL58/
As long as the "loading..." image is positioned before any other html elements, it should load first. This of course depends on the size of the image. You could put the loading div right after the tag and position it using 'position:absolute'.
Regarding the code to remove the loading screen, one method is to do the following.
Put all the images, scripts that need to be loaded in a hidden div (display: none)
Set up a variable that will hold the total of the images / scripts to be loaded
Set up a counter variable
Attach to each image / script the "onload" event
Everytime the "onload" event is triggered it will call a function that will increment the counter variable and check if the value of the counter equals the value of the total variable
If all resources have been loaded, fire a custom event that will show the div with the images, and hide the div with the loading screen.
The code below isn't tested so it might not work. Hope it helps
var totalImages = 0;
var loadCounter = 0;
function incrementLoadCounter() {
loadCounter++;
if(loadCounter === totalImages) {
$(document).trigger('everythingLoaded');
}
}
function hideLoadingScreen() {
$('#loadingScreen').hide();
$('#divWithImages').show();
}
$(document).ready(function(e) {
$('#loadingScreen').bind('everythingLoaded', function(e) {
hideLoadingScreen();
});
var imagesToLoad = $('img.toLoad');
totalImages = imagesToLoad.length;
$.each(imagesToLoad, function(i, item) {
$(item).load(function(e) {
incrementLoadCounter();
})
});
})
I'm not sure if it's possible to enforce.
If it is, try adding this in the head-tag:
<script type="text/javascript">
if(document.images)
(new Image()).src="http://www.image.com/example.png";
</script>
In theory that may load and cache that image before anything else.
I think if you place the IMG tag at the top of your html body it will be loaded first. If you do not want to move your div just use a copy of the image tag. Once the images is loaded it will be shown in every image tag which shows the same picture.
Or you could use spin.js as loading image. It display this "loading cycle image" via javascript.
Check it out under:
http://fgnass.github.com/spin.js/
how to display the image at last after loading all the other contents in a webpage.
I've an image on a page which is retrieved from the database when a button is pressed.
I'd like to load entire page first and the image at last after the contents are loaded.
any help?
If by load you mean download the various parts of the page and construct the DOM, then:
$(document).ready(function() {
$('#theimage').show();
});
You can load and add it to your html it in javascript using this function:
$(window).load(function() {
// in 2 steps for clarity, can be optimized
img_html = '<img src="/path/to/image" alt="bla bla" />'; // step 1, generate image html
$("#image_div").append(image_html); // step 2, append image to some div
// optional, see my comment below
$("#image_div img").load(function() {
// triggers when newly added image is completely loaded
});
});
That makes sure loading of the image starts when everything else has finished loading.
Note that the image in the example shows while loading, if you want to load it first and then display it, you'll have to hide it and use the .load event of the image to display it.
$(document).ready(function() {
$('#imageid').attr( "src", "/new/path/to/image.jpg" );
});
In your initial load of the page you can just write a placeholder (div, span, even an image with nothing assigned to it.)
Then attaching to the button click event you can use JQuery + Ajax to callback (not postback, or is there any reason for the postback OTHER than to get the image?) to your server (or a webservice) to get the image path and assign that to the place holder. You can augment that with various jquery animations to "fade in" your image or slide down... what ever you like.
can you use javascript to dynamically set the image url after the dom loaded?
If you have html structure
<image id="image_id"/>
Then use the following jquery code:
$(document).ready(function() {
$("#image_id").attr("src", "link_to_image");
});
Or else, you can use some css trick, hide the image first, so it won't download from server.
Then use the following jquery code to show the image once DOM is ready:
$(document).ready(function() {
$("#image_id").show();
});
At the same time, looks at image preload. this may be useful to you http://www.techrepublic.com/article/preloading-and-the-javascript-image-object/5214317
I have a slight problem.
I need to show some safety information in a JS drawer that the page loads with open. The images creating the drawer are kind of hefty and as such the safety text in the drawer render prior to the background, creating a really ugly loading experiance. Is there a easy way I can say
DO NOT LOAD safetyText UNTIL safetyBG is loaded ?
We're not using any libraries (i.e. jQuery) so a JS solution would have to work as a script by itself.
If I understand you correctly, you only want to display safetyText once safetyBG has fully loaded. To achieve that, hide safetyText, then check on document.onload if safetyBG has loaded. If so, show text, if not, attach function to show text to safetyBG.onload:
function showSafetyText() {
//show text
}
window.onload = function() {
var safetyBG = document.getElementById("safetyBG"); // tweak as necessary
//have to check to see if img loaded, if you would simply assign showSafetyText
//to img.onload, it would never run if the img was fully loaded already
if (!safetyBG.complete) {
safetyBG.onload = showSafetyText;
} else {
showSafetyText();
}
}
You mentioned images (rather than a single image) in your post. If that's the case you'll want to write a function that loops through the images to check to see if they've all loaded (at which time you can load the text); then attach this function to each of the images' onload events (unless all images are loaded already in which case you can simply show the text).