This may be a dumb question, but I've a real confusion and want to get an opinion from somebody who knows this in-out.
Preloading images can be done either via JavaScript or CSS (to name two which I'm considering). I read the tutorials that if the browser finds the same image path again, it would render the cached image.
If I preload images like:
<img src="../images/bg.jpg" alt="background" width="1" height="1" style='display:none' />
and
<img src="images/bg.jpg" alt="background" />
Similar with javascript:
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
});
}
// Usage:
preload([
'../img/imageName.jpg',
'img/imageName.jpg' // case when using this script in a different hierarchical level)
]);
Will the second call result into rendering of the image from the cached version or it will not work because the image path specified is different (though ultimately it refers to the same file).
Thanks in advance.
I realise this is and old one but I get this one all the time from interns - so here goes...
Even though the onload function is in the JS file asking/telling the browser to look for the image; it is the browser looking for the image and is telling the JS that the image/s loaded.
So your image path in the JS should be the same as how you would enter it in the HTML.
PS: I noticed in your HTML the image folder is "/images" and in your JS the folder is "/img"
Related
I want to block all the images of any web page to lower the page loading time, consider the web page source code is loaded into browser but the documents/files still needed to be downloaded, is there any event to cover this problem?
I think can method must be followed in browsers text only mode.
No. If the src tag is already set the browser will Load the images no matter what. Remove the src tag after it was loaded doesn't change the fact that it was already downloaded.
The only way to avoid this is to set the src tags of imgs by Javascript dynamicly. And therefore not set images if you don't want to.
You can't make the browser not loading images if it's already in the html.
I'm not sure if it solves your problem but maybe you can try this:
<script type="text/javascript">
$(document).ready( function() { $("img").removeAttr("src"); } );
</script>
<div class="image"><img external-src="original.jpg" src="fake.jpg" /></div>
$(window).load(function(){
$('.image img').attr("src", $(this).attr('external-src')).removeAttr('external-src');
});
This will load all the images after whole dom loaded
You can remove the whole img tag
$("img").remove();
or you can just remove the image tag source attribute
$("img").removeAttr("src");
or you can just replace all the image source having shorter loading time
$("img").attr("src",'http://someimage.jpg');
I have a little generated JavaScript from a JSP page that looks like this:
var elem = document.getElementById("image");
elem.src = "Image?step="+step;
The code snippet above is called when the user clicks on a button, and step is a variable that is increased with every run of the function. Image is a Servlet that generates a PNG-encoded Image.
This works, but it is very slow because the Server must generate the Image when the Client wants it. I know I could pre-load the Image, but I thought of a better solution. Since I know how many steps are allowed, I thought of generating the Images when the page is requested, and embed them into the JavaScript, maybe Base64-encoded so that the Image can be viewed on all OS.
Is it possible to do this? If yes, how could I implement it? I don't want to use external JavaScript frameworks like jQuery, and I don't care about browsers that are not really common, it'll be enough if it works with Mozilla browsers and Google Chrome.
If you only want to embed the image source into a HTML page, you can do the following:
<img id="image" src="" width="100" height="100" alt="" />
<script type='text/javascript'>/* <![CDATA[ */
var img = '<?php echo base64_encode(file_get_contents('/path/file.png')); ?>'
document.getElementById('image').src = "data:image/png;base64," + image;
/* ]]> */</script>
This is supported by pretty much all browsers: http://caniuse.com/#feat=datauri … “Partial support” for IE means that it is limited to images and CSS, but images is what we do here.
Example: http://jsfiddle.net/m869e2ar/1/
I'm running a Javascript replace function to replace standard images with class="replace-2x"on my jQuery Mobile site with Retina-quality images if the user is on a mobile device with Retina display. For example, on a Retina device, logo.png will be replaced with logo#2x.png. The JS function is here:
function highdpi_init() {
$(".replace-2x").each(function () {
var src = $(this).attr("src");
$(this).attr("src", src.replace(".png", "#2x.png").replace(".jpg", "#2x.jpg"));
});
}
$(".page").live('pageinit',function(event){
highdpi_init();
});
I'm now running into an issue where the replace function is running more than once. So for example, it replaces logo.png with logo#2x.png as the page is loading, but then as the page continues to load, it KEEPS replacing .png with #2x.png in the img src over and over so that the image tag ends up looking like this:
<img src="mobile/images/logo#2x#2x#2x#2x#2x#2x#2x#2x#2x#2x#2x.png" class="replace-2x" alt="logo" width="200">
How can I prevent this from replacing on a single img element more than once? Keep in mind, I will have multiple images on the same page, so the function will need to apply to all images, but only one time each.
The problem is surely that your 'pageinit' event is being called more than once. You can either follow MДΓΓ БДLL's idea (which won't work if images are dynamically added) or you can make your handler smarter so that it doesn't replace the src if it already was replaced
function highdpi_init() {
$(".replace-2x").each(function () {
var $this = $(this);
var src = $this.attr("src");
$this.attr("src", src.replace(".png", "#2x.png").replace(".jpg", "#2x.jpg"));
// Remove the class so it doesn't replace it again
$this.removeClass('replace-2x')
});
}
You don't need JS for this, you could do it in CSS only.
<link rel="stylesheet" media="only screen and (-webkit-min-device-pixel-ratio: 2)" href="/css/highdpi.css"/>
You could make your images look like
<img src="transparent.gif" class="logo-a" alt="logo" width="200" />
And in highdpi.css you could do
img.logo-a {
background-image: url('file#2x.png')
}
And in lowdpi.css
img.logo-a {
background-image: url('file.png')
}
Using .one() should work since it is just a binding and if you are using Jquery Mobile the way that is suggested it will be just fine. That is unless you are passing back the html from the server. In which case it would be a good idea to add an extra condition to make sure that the src doesn't already have #2x.png before replacing.
There is disappointingly little documentation on pageinit on the offical jQuery Mobile docs. So I'm going to speculate here. It looks like pageinit is used to fire events for when a specific DOM element has finished loading, since it may not have been loaded on the initial page load (deferred until needed). That being said, it may be that adding/altering images to the DOM element in question fires the pageinit again. Could you tag each updated image with something that says, 'hey, I've already been updated to 2x'? Something such as
$.data(targetimg, 'retinafied', true);
And then check for that value before replacing the src?
I have a web page where lots of images called from server using image
scr attribute.
I have created a function like which is triggered by td click.
function GoToStep(stepNo) {
var imgSrc = $("#h1" + stepNo).val();
$(".img_vertical").css("background-image", "url(" + imgSrc + ")");
}
Now the problem is this. For slower connections the images come after some
moment.
Can I pre load images to avoid waiting time when user clicks
td?
I have seen some jquery function to pre load images.
Kindly give some idea how can I achieve it.
Pre-loading an image is equivalent to loading an image but never displaying it. So, you can easily do it like this:
<img src="image.png" alt="" style="display:none;"/>
Now this image will be loaded as soon as the html starts rendering. Whenever you need to use this image as a display or background, just set the address to image.png and it will automatically be fetched from browser's cache.
This can be done using some javascript functions. Quoting from another question.
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);
Explanation of how javascript preloaders work (different question)
[...] The way it works is simply by creating a new Image object and setting
the src of it, the browser is going to go grab the image. We're not
adding this particular image to the browser, but when the time comes
to show the image in the page via whatever method we have setup, the
browser will already have it in its cache and will not go fetch it
again. [...]
So in your case, you should use something like
$(function() {
// Do stuff when DOM is ready
preload([
'img/bg1.jpg',
'img/bg2.jpg',
'img/bg3.jpg'
]);
});
To be more specific, I want to use a form with one or more file input fields used for images. When those fields are changed, I'd like to show a preview of the associated image, before sending the data to the server.
I've tried a number of javascript approaches, but I always run into security errors.
I wouldn't mind using java or flash, as long as the solution degraded gracefully for those users who didn't have them. (They wouldn't get previews, and they wouldn't get an annoying 'install this thing' either.)
Has anyone done this in a simple, reusable way?
P.S. I know there's a sandbox, but does the sandbox have to be in a dark, locked room with all the windows blacked out?
No need for fancy stuff. All you need is the createObjectURL function, which creates a URL that can be used as the image src, and can come straight from a local file.
Let's say you selected a couple of images from the user's computer using a file input element (<input type="file" />). Here's how you would create previews for image files for it:
function createObjectURL(object) {
return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object);
}
function revokeObjectURL(url) {
return (window.URL) ? window.URL.revokeObjectURL(url) : window.webkitURL.revokeObjectURL(url);
}
function myUploadOnChangeFunction() {
if(this.files.length) {
for(var i in this.files) {
var src = createObjectURL(this.files[i]);
var image = new Image();
image.src = src;
// Do whatever you want with your image, it's just like any other image
// but it displays directly from the user machine, not the server!
}
}
}
The first step is finding out the image path. JavaScript is allowed to interrogate the upload control for a filename/path, but (for reasons of security) various browsers show different things to the JS engine than they display to the user - they tend to keep the filename intact so you can at least validate its extension, but you may get c:\fake_path\ or some similarly obfuscated thing prepended to the filename. Trying this on various browsers will give you an idea as to what gets returned as a real path, and what gets faked out, and where.
The second step is displaying the image. It's possible to display local images if you know their paths, via img tags with file:// source URLs, if the user's browser allows the file:// scheme. (Firefox doesn't, by default.) So if you can get the user to tell you what the full path to the image is, you can at least try to load it.
JavaScript has no access to the local file system for security purposes, period.
Here's a jQuery + PHP script for uploading an image an previewing it.
I have only ever seen Java applets that do this, for example, the image uploading applet on Facebook. The downside to the Java approach is that the user will be prompted to trust the applet before it runs, which is a kind of annoyance, but this allows the applet to present a file browser with image previews or do more interesting things like allows the user to upload an entire directory.
You can try this approach, although it seems it doesn't work on IE.
http://saravani.wordpress.com/2012/03/14/preview-of-an-image-before-it-is-uploaded/
It's simple and fast to code.
I put the code here just in case the source dies:
Script:
<!-- Assume jQuery is loaded -->
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img_prev')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
In the HTML:
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="img_prev" src="#" alt="your image" />
</body>