I want to synchronize web site like when page load first it will load content then images then flash content then another content.
Like i have seen the same at http://gmailblog.blogspot.com/ [ see how images load ]
Is there any way to achieve? Any link or source code would be appreciated.
I seen the web site. This is the same thing that happens with bing. How to do this ?
In the core HTML code give the <img src="loading.gif" id="1"/> or whatever element you want.
When the Core HTML is done, before the </body> tag, use javascript to change the
attributes values (for eg. "src" attribute of the img element). Remeber the javascript need to be written at the end of the HTML before closing the body tag. The browser will load the
contents accordingly in sequence. This can be used to achieve priority based loading of HTML components.
You can synchronize loading of all elements on your page by controlling it using JS. For ex: one strategy to load images after content would be:
a) In your html, instead of in the src attribute, specify the image location in another attribute, say 'isrc'.
b) Inside your onload callback (assumes you're using jQuery):
var loadCounter = 0;
$('img').each(function() {
if($(this).attr('isrc')) {
this.onload = function() {
loadCounter++;
if($('img[isrc]').length == loadCounter) {
// .. proceed to loading other stuff like flash etc..
}
}
$(this).attr('src', $(this).attr('isrc')); // load the image
}
});
Related
I am working on a web widget that can be embedded on 3rd party websites.
Since a lot of content management systems do not allow users to post/execute scripts, I want my widget to show an image instead of JS-generated content if such situation occurs.
<script type="text/javascript">
(function(){var s = document.createElement('script');s.src = '//example.com/file.js';s.async = "async";document.body.appendChild(s);}());
</script>
<img src="//example.com/image.svg?param1=value1" src="" id="my_fallback">
For now I am using the code above. Is there any way to show the image only if the script did not load? The goal is to reduce transfer usage and provide better user experience.
The first line of my widget script is removing #my_fallback, but it is not fast enough - sometimes I can see the image for a second before the actual widget content replaces it.
The only thing I came up with is to delay creation of the image by including something like sleep() in the beginning of my image generator.
EDIT
No, <noscript> won't work here. I do not want to fallback if user has disabled javascript. I want to fallback when a script has not loaded - for any reason, especially if some security mechanism cut off the <script> section.
Use html tag Noscript
<noscript>Your browser does not support JavaScript! or a image here</noscript>
Remember
In HTML 4.01, the tag can only be used inside the element.
In HTML5, the tag can be used both inside and .
Edit : -
add one html tag
<span class="noscript">script is loading.....or put image</span>
inside your script tag
now in your scripts which has to be load add one code like
add this line at the end
$('.noscript').hide();
This is the other way which you can handle the same!
One quick fix is to create a global variable from that script, visible to the window object.Also the image must be hidden. Then, on a main.js script check for that variable. If it exists then run your widget code from there. If it doesnt exist then fadeIn the fallback image.
Heres a demo
The default img is an image 272x178 size and the widget image is an image 300x400 size.
To simulate the action when the script is unavailable, just name the variable myWidgetIsEnabled with a different name so the condition fails.
Here is some code:
// Code goes here
var widget = (function(){
window.myWidgetIsEnabled = true;
return {
init: function(){
var s = document.createElement('script');s.src = 'file.js';s.async = "async";
document.body.appendChild(s);}
}
}());
$(document).ready(function(){
if(window.myWidgetIsEnabled){
widget.init();
}else{
console.log('not enabled, the default behavior');
$('.fallback').fadeIn();
}
})
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).
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.