Is it possible to run javascript before images begin loading? - javascript

I'd like to change the src attribute of images before they are requested by the browser, the aim being to reduce the size of the images using a PHP script like Timthumb. Using jQuery, I thought $(document).ready would do the trick:
$(document).ready(function () {
var imgs = $('#container img');
jQuery.each(imgs, function() {
$(this).replaceWith('<img src="timthumb/timthumb.php?src=' + $(this).attr('src') + '&w=200" />');
});
});
But the original, unresized image is still downloaded in the background to the browser's cache. Is it possible to do what I'm trying to do on the client side, or is server-side the only option?

Javascript loading and execution is serialized by the browser (unless you use something like head.js), but the problem is that the DOM has to be available for a script to modify it. The jQuery ready event fires after the DOM is available, so the browser has already started requesting the resources that were referenced in the HTML.
So if you put the Javascript before the image tag it won't be able to find the image tags, and once ready fires the download has already started. I'm not aware of any events that fire before image load (just one for aborts), so the cleanest method is to create the HTML with the modified src attributes in the first place.
Alternatively, put the src in a different attribute on the image (like data_orig_src) and run the script to set src to data_orig_src on each image upon document ready. Use CSS to hide the images before changing the src so the user doesn't see a broken image icon. I think this is probably better than adding the images after the fact because you won't need to track where the images need to be placed in the DOM, and it should perform better as well.
Of course if you can change the server to use data_orig_src instead of src, why not just put the proper src in the tag in the first place...

You cannot change the DOM of the page before the DOM has been loaded. And, once the DOM has been loaded, the browser has already started requesting images. So, you cannot change <img> tags before they start loading their images.
What you could do is change the source of the page to not have any of the images you want to change in the source of the page and then use javascript to dynamically insert the desired images after the page has been loaded. This way the browser will never request the wrong images.
Or, you could change the <img> tags to not have a .src property at all and with your Javascript you would add the .src property. An <img> tag with no .src property will not display until you provide it with a .src property.
If you're worried about the wrong images flashing as they are loaded before you change them to the correct images, you can use CSS in a stylesheet to hide the images initially and then after you change the img.src to the correct value and that new .src value has loaded, you can make them visible.
If you can't change the source of the page, then all you can do is hide the images initially (using CSS) until the correct .src has been set on them and that new .src value has been loaded.

It is sort of possible but not in the way you currently have or probably want and it doesn't degrade gracefully but you can take the image out of your html and use jQuery to insert it into your html and apply whatever changes you want to it.
Example:
var image = $('<img />').attr('src', 'imageURL.jpg');
image.appendTo('domElement');
But doing it like this it doesn't make any sense to me as to why you wouldn't just edit the image source anyway.

Related

Avoiding multiple GET requests due to un initialized value of SRC attribute in IMG element

I have an img element with src attribute
<a><img src="{imgSrc}" alt="Image"></a>
The value of imgSrc is generated dynamically when a certain user induced event happens after the page loads.
My problem is, when the page loads there are a bunch of GET requests being sent to the server since there are many src attributes with imgSrc for the URL and as expected they return 404 errors since the imgSrc is not constructed by the time.
My question is, is there any way to make sure that the request is not sent to the server when imgSrc variable is not populated with an image URL.
Additional details:
This is fully developed web application by some one else and I am fixing defects in this.
The developer has designed the application in such a way that almost all src attributes have variable for their URLs and loaded when the page loads, but the URL values are generated only when certain events happen.
Unfortunately, browsers will try downloading the resource specified in the src attribute of img node elements as soon as this attribute is set.
This happens even if the img elements are not inserted into the DOM! They just need to be transformed from HTML string into node elements within the current document context (but not necessarily its DOM).
So if you cannot manipulate that HTML string before it is parsed by the browser, there is absolutely nothing you can do to prevent it from trying to fetch the resources.
A dumb workaround would be to provide a dummy image (like a transparent 1px * 1px?) with that exact name, so that browsers are happy and stop requesting it…
If this is an option for you, you could try replacing the entire img tag (rather than just its src value). But you will need a way to hide the placeholder text so that the user does not see it before you replace it by an actual img tag.
Good luck!

Site with many images, load only some images?

I have a site that show many images hosted in a server. In the page, the images are situated in of max 100 images. In a single moment, only one div is displayed (throw the css style "display") and the others have the display:none.
I need a way that allow me to load only the images of the div displayed because when I open the site, it loads all the images.
when You are using display:none - the images are still being downloaded. But if You'll use display:none on background-image they won't. Another approach is to make a button "Load more..." and asynchronously request the rest of the images
your can hide the images which you dont want to display on page load, try following code in document.ready function
$(document).ready(function(){
$("#img1").hide();
$("#img2").hide();
$("#img3").hide();
.
.
.
$("#img_n").hide();
});
One way you could do it is by making a large image sprite, which you will upload and let the browser cache it.
A good explanation about CSS sprites can be found here: http://www.w3schools.com/css/css_image_sprites.asp
Just leave the img tag's src="" blank on all but the first image and modify it with javascript.
You can use an onload event to trigger setting the next src property.

How can I replace an image with an SWF on click, and revert back to the image when another image is clicked and replaced with an SWF?

Let's say I have 3 images, each a placeholder for a Flash animation. When I click an image I want it to be replaced by its corresponding SWF. When I click another image I want the current SWF to be replaced by its placeholder image, and the newly clicked image to be replaced by its SWF.
I'm thinking of using the data attribute on the images to hold the path to the SWF…but this doesn't seem like the cleanest way to accomplish what I want.
IMAGE and SWF are quite different object. The first is a simple block element, the second is a more complex object/embed.
The simpliest way i see to achieve what you want is to load both image and swf, maybe in 2 different DIVs, and then swap them trough javascript, setting the "display" style as you wish.
Another way is create a DIV for each image and, always through javascript, dinamically rewrite the content on "click" event. Cleaner, but a bit more complex.
You can replace the html code using .replaceWith().
BUT each time you will replace html to Flash, your animation will be restarted.
It means :
Replace html->swf : Flash Player loads SWF
Replace swf->html : Flash Player unloads SWF
I'm not talking about the SWF downloading (you can use cache for this) but only the SWF application loading.
Depending on your needs, this solution can fit but IMO you should think about not using Flash.
By the way, working with display: none; or .hidden (e.g.) will have the same effect as replacing html code.

How to preprocess HTML before it is parsed by the browser - block resorce loading

I am looking for a way to modify some text inside the HTML before it is being parsed by the browser.
More precisely, I would like to remove some tags from the HTML so the image resources would not be fetched by the browser, only when I am ready I could insert these tag back to have them loaded.
Is it possible to do that via some JS/Jquery or CSS, if so, how?
the motivation here is to be able to block the loading of some resources on a page and have them loaded only when needed according to some logic. this needs to be done by some kind of scripting added to the page
Because you're doing this in JavaScript the HTML is already being processed when it comes to launch your <script> tags.
You could move your <script> tags into the <head> from the <body>, or move it to the very beginning of the body. However the problem here is that you'll have to wait for your elements to actually be created in the DOM before you can work with them.
You could use something like setTimeout() or similar and continually look for them until you find them, but there's still going to be a slight delay between them being created and your script finding them, at which point they might already start to load.
The only surefire way is to process the markup server side long before it gets to the browser.
My answer here possibly could be of use, if you can place noscript tags in key places in your markup prior to parsing/evaluation:
Client-Side Dynamic Removal of <script> Tags in <head>
This method—for javascript-enabled agents—would delay the rendering of the entire page however, or at least the regions that you needed to affect.
basic generalised theory
Wrapper your body or specific region with a noscript tag identified with either a class or id. Place some javascript to execute directly after the close noscript that grabs the tag and reads the html contents as a string. At this point you could modify the html string however you like and then re-inject it back into the DOM replacing the noscript tag.
more specific implementation
If you know before-hand which resources you need to postpone—say all your images—you could wrap each image in-question with a noscript tag. Then trigger off some JavaScript that grabs all noscripts and rewrites the contained image html to use a placeholder or lower quality version of the image. At the same time you could set up event listeners or timeouts that inject the actual images when the time is right.
The Lazy Load Plugin for jQuery is maybe what you are looking for. It delays loading of images in long web pages.
You can use any jQuery event such as click or mouseover. You can also use your own custom events such as foobar. Default is to wait until user scrolls down and image appears on the window.
Beside all the It is also possible to delay loading of images. Following code waits for page to finish loading (not only HTML but also any visible images). Five seconds after page is finished images are loaded automatically.
$(function() {
$("img:below-the-fold").lazyload({
event : "sporty"
});
});
$(window).bind("load", function() {
var timeout = setTimeout(function() {
$("img.lazy").trigger("sporty");
}, 5000);
});
Check the delayed loading demo.

Wait for a particular image to load completely using jquery?

I am currently using the code below to load images but I want to show some kind of loading gif before the image loads completely.
$('#addimage').attr('src', src[i]);
$('#addimage').show();
Since I am using this in a animated mediabox the image loading in blocks does not look good so by the time the image is loading I want to replace it by showing a loading gif. Thanks
Use the load() event:
$("#addimage").load(function() {
$(this).show();
});
Edit: to show one image until another loads is a little more convoluted but entirely possible. See Image Loading.
You can use the callback event for once the image has loaded. Something like:
$('#addimage').load(function() { $(this).show() });
$('#addimage').attr('src', src[i]);
So you setup the load handler first, then apply your src attribute. This is assuming the image is hidden by default (via CSS, etc).
You can bind the onload event to the image.
Why not just set the src attribute to point to a loading image (EG, animated gif) and just show it the whole time?

Categories

Resources