Javascript document.write() - Replace PNG with GIF? - javascript

The Scenario
I have an asp.net web application with a HTML/CSS front end.
This all works fine but in Internet Explorer 6, the transparent PNG's that I use within the site are not transparent due to the poor design of this particular browser.
Solutions Attempted
I've already attempted various IE6 PNG Transparency fixes that didn't work.
The Proposed Solution
I thought about using GIF Image replacements for when the website detects that the browser is IE6. I don't have any javascript experience but someone has mentioned that I could use the "document.write()" feature off javascript to replace the PNG's with GIF's of the same image when using IE6 as the browser.
The Question
Please could someone explain to me how I would go about doing this?
Baring in mind I have an understanding of C# etc. but no javascript knowledge. I'm only just starting out as a web developer so simple explanations would aid me greatly.
Thanks for the help.
Regards.

If we assume that
a) the gif files will have the same name and,
b) they already exist (you're not looking for some gif creator).
Then you just need to replace the src attribute for these files. This would be done onload, and doesn't require document.write(). Go with:
<!--[if lte IE 6]>
<script type="text/javascript">
window.onload = function() {
var images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
var image_png_src = images[i].src;
var image_gif_src = image_png_src.replace(".png", ".gif");
images[i].src = image_gif_src;
}
};
</script>
-->
The nice thing about the above method is that it doesn't have to check if it's gif or png or jpg every time, because it simply won't replace it with .gif unless there is a .png. The bad thing is that if, for some reason, you have an image with .png in it (and I can't imagine why) but it isn't the file extension, it would replace that bit with .gif.
Hope that helps.

Have you tried jQuery's pngFix? It makes the PNG transparent for IE 6 and you don't need to maintain two sets of images (PNG and GIF).
Using it doesn't require much javascript knowledge, so it wouldn't hurt to take a look at it.

Let's say your img element has an id="my_img"
To detect if browser is IE6, use conditional comments. Further, add Javascript like this:
<!--[if IE 6]>
<script>
document.getElementById("my_img").src = "images/alternate.gif"
</script>
<![endif]-->
You might also like to have a look at this:
IE6 PNG transparency

Here is the code runs a replace on IE6 only:
window.onload = function() {
if(navigator.userAgent.match(/MSIE 6/) != null)) {
var images = document.getElementByTagName("img");
for (var i = 0; i < images.length; i++) {
var src = images[i];
if(src.match(/\.png$/)){ //endswith .png
images[i].src = src.replace(/\.png$/g,'.gif');
}
}
}
};

jQuery version of the replacement:
$(document).ready(function()
{
// List all PNG images
$("img[src$=.png]").each(function(i, img)
{
// Replace with GIF versions
img.src = img.src.replace(/\.png$/, '.gif')
});
});

W3Schools is a great place to start if you're wanting to learn javascript.
For example, take a look at the getElementsByTagName function...
There is also a browser detect function here
Good luck - hope that helps.

Related

Fastest way to preload/load large images

Preload may not be the correct term...
I have a page which loads a very large image. I wanted to wait for the large image to completly load before displaying on the page for the user.
At the moment, I have a loading gif and i'm using javascript to wait for the image to load and then replace the loading gif src with the image:
<img src="loading.gif" id="image" />
<script>
img = 'very_large_image.jpg';
var newimg = new Image();
newimg.src = img;
newimg.onload = function(){
$('#image').attr('src',img);
}
</script>
I'm wondering if there are quicker ways to load this image such as a pure CSS way or some way to force the browser to download this asset first. The code above is obviously positioned in the location where the image is expected to load. So there is code above and below.
One CSS option I thought was to position the image off the screen and once it's loaded, perform the src replace.
My server is running http2, so it should be pretty quick. I just want to know if there is a better way then what i'm doing now to ensure the large image is loaded the quickest way possible for all major browsers.
I should add, i've already done plenty of optimisation of the image file already. I'm working with high resolution photography.
Thanks!
You can make the JPG progressive and then just let it load. Browsers will progressively display the image first blurry and then load more details.
This is the best way because user can see the image even before it's fully loaded.
Edit:
On linux use jpegtran, on Windows use Photoshop or RIOT
Your doing a great job!
Here is what I came up with:
https://jsfiddle.net/Vandeplas/jkwweh52/
HTML:
<img src="http://loadinggif.com/images/image-selection/32.gif" large-src="http://www.planwallpaper.com/static/images/518079-background-hd.jpg" large-class="fancyImg">
JS:
$('img[large-src]').each(function() {
var img = $(this);
var newimg = new Image();
newimg.src = img.attr('large-src');
newimg.setAttribute('class', img.attr('large-class'));
newimg.onload = function() {
img.replaceWith(newimg);
};
});
That separates the JS from the HTML + you can easily add infinite more pre-loading images without having to change the js!
Very easy way to preload images which are needed later
$.preloadImages = function() {
for (var i = 0; i < arguments.length; i++) {
$("<img />").attr("src", arguments[i]);
}
}
$.preloadImages("hoverimage1.jpg","hoverimage2.jpg");
I think that the best solution for your problem is split this image and load the parts assync at the same time

How to use window.location with randomized objects?

I've made a site that randomizes HTML videos or images just to practice my javascript.
I am trying to make it so that each time a video is randomized the URL location will change to represent the new video, this way users would be able to link directly to a video that was randomized.
Currently it only displays a static url that does not change whenever content is loaded.
Here is the obligatory codepen
Codepen
function chooseRandomVideoFromList() {
var i = Math.floor(Math.random() * currentList.length);
var video = currentList[i];
var $video = $('video');
// clear
$video.html('');
// <source src="" type="">
video.sources.forEach(function (source) {
var $source = $('<source>').attr('type', source.type).attr('src', source.src);
$video.append($source);
});
Any help or advice would be greatly appreciated, i've read the documentation and I am still stumped :S
Thanks guys!
You cannot directly write on the window.location.href property, but you may change your sites url with the html5 history api and pushstate.
Example:
history.pushState({}, "Stackoverflow", "http://stackoverflow.com");
This should work in all modern browsers, see: http://caniuse.com/#search=pushstate
More information on this topic could be found here: https://developer.mozilla.org/de/docs/Web/Guide/DOM/Manipulating_the_browser_history
Though keep in mind you need also to listen on popstate events if you want the users to be able to use their browsers back and forward buttons. Also your server side code needs to handle the urls.
If you need to support older browsers or don't want the server side to be involved you could set the window.location.hash property instead which does not change the url itself but let you change the hash part of the current url, for example:
window.location.hash = "uri=stackoverflow.com";
This way you might store the Index of the video currently shown. When loading the page you might want to check if there's a value in "window.location.hash" and if it is a valid index for your videoFiles. If so you should play that video.
Example (insert in your starting code):
if (window.location.hash !== "") {
showSpecificVideoFromList(window.location.hash);
}
And this one in your chooseRandomVideoFromList:
window.location.hash=i;
Then implement your showSpecificVideoFromList in order to show the given index (and check for validity)

html5 Image Filters with Canvas

I have download the source from this http://www.storminthecastle.com/projects/imagefilters1/. It is regarding some image manipulation in html5 canvas.
Inside the source, it will load the image located in a local directory...
function reset() {
imageURL = "./sandbox.jpg";
imageFilter = grayscale;
document.querySelector("#filename").innerHTML = "";
update();
}
The above is working in my project. But I am trying to load an image from an url, so I modified it to the following...
function reset() {
imageURL = "http://xxxxxx.jpg";
imageFilter = grayscale;
document.querySelector("#filename").innerHTML = "";
update();
}
When I test it, the image is being displayed correctly. However, all the features are not working anymore and I don't know why. I have no idea why it cannot take in url as the argument and I don't know how to modify it to make it work. Any helps?
Thanks for the link provided. I further read on the COR issue and managed to locate that line of coding to be added.
img.crossOrigin = '';
//img domain different from app domain
img.src = 'http://xxx.jpg';
Simply set the crossOrigin property of the image to make it work. Basically, this will allow cross domain image for manipulation. Without it, any cross domain will be blocked and you will get the security exception. Really thanks for the helps! :)
To add-on, I have only tested using Chrome and is working.

Javascript image preloading, I'm doing something wrong

I'm using document.images to load images when a visitor first visits the website. The reason is because I have a few different areas which have rollover images. Before I switch over to using CSS sprites (modifying a lot of work), I'm going to ask here.
So I'm preloading images with this:
images = new Array();
if (document.images) {
images.push(preloadImage("http://website.com/images/myimg.png", 300, 200));
}
function preloadImage(src, x, y) {
var img = new Image(x, y);
img.src = src;
return img;
}
And according to Chrome's "resource" panel, this is working just fine. Even after pressing CTRL+F5, the images listed in the JS are downloaded.
HOWEVER, they are not used. If I hover over an element in one of my three scripts, the image is downloaded a second time. Derp?
I assume that when preloading images this way, you're supposed to put that image array to use. I thought the browser would be smart enough to say "Hey, this is the same image, let's use it twice" but apparently not.
So is this correct? Do I need to rewrite my programs to preload images individually? I know it doesn't sound hard, but it's really not designed for that.
This is not really an answer to your question, but I proprose a different solution. Put all the images you need to preload inside a div that is hidden from the user. I know, I know, this i not as elegant, but it should work just fine. :)
<div style="display: none;">
<img src="http://website.com/images/myimg.png" alt=""/>
...
</div>
This works fine for me:
function imgPreload() {
var imageList = [
"my/firstimage.png",
"my/secondimage.jpg",
"my/thirdimage.png"
];
for (var i = 0; i < imageList.length; i++ ) {
var imageObject = new Image();
imageObject.src = imageList[i];
}
}
imgPreload();
Cheers. Frank

Removing images with Greasemonkey?

I would like to stop images from loading, as in not even get a chance to download, using greasemonkey. Right now I have
var images = document.getElementsByTagName('img');
for (var i=0; i<images.length; i++){
images[i].src = "";
}
but I don't think this actually stops the images from downloading. Anyone know how to stop the images from loading?
Thanks for your time and help :)
If you want to disable images downloading for all websites (which I guess you might not be doing) and are using firefox, why not just disable them in preferences? Go to the content tab and switch off "Load images automatically".
Almost all images are not downloaded. So your script almost working as is.
I've tested the following script:
// ==UserScript==
// #name stop downloading images
// #namespace http://stackoverflow.com/questions/387388
// #include http://flickr.com/*
// ==/UserScript==
var images = document.getElementsByTagName('img');
for (var n = images.length; n--> 0;) {
var img = images[n];
img.setAttribute("src", "");
}
Use a dedicated extension to manage images (something like ImgLikeOpera).
If you'd like to filter images on all browser then a proxy with filtering capabilities might help e.g., Privoxy.
I believe greasemonkey script are executed after the loading of the page, so I guess the images are loaded too.
Not entirely related, but I use this bit of code to toggle displaying of images in Firefox in the EasyGestures plugin. I am not sure if this can be translated to greasemonkey, but it might be a starting point.
var prefs = Components.classes["#mozilla.org/preferences-service;1"].
getService(Components.interfaces.nsIPrefBranch);
var nImgPref = prefs.getIntPref("permissions.default.image");
if (nImgPref == 1) {
prefs.setIntPref("permissions.default.image",2)
alert('Images off.');
} else {
prefs.setIntPref("permissions.default.image",1)
alert('Images on.');
}
I know it's not greasemonkey, but you could try the "IMG Like Opera" extension. It definitely keeps the files from downloading, and has more flexibility than just on/off.
Do you know that the images still load? Maybe you should assert it using Firebug or some such?

Categories