Adding favicons with generic option - javascript

I'd like to add favicons to my site using favicon.ico.
however I want to load a generic icon if the site does not provide one.
How can I test for the presense of a favicon and if one is not present manipulate the DOM to point to a generic favicon on the server.

You could use some JavaScript. Adapt to suit...
var img = document.getElementsByTagName('img')[0],
favicon = new Image;
favicon.onerror = function() {
img.src = 'http://some-other-url.com/favicon.ico';
}
favicon.src = 'http://example.com/favicon.ico';

Found this link, wish I would have found this sooner.
<img src="image.gif" onerror="src_to_generic()" />
at
w3 schools
Just call a function on the onerror that resets the src to a generic image.

Related

HTML, how to set multiple src attributes for image in parallel, fastest win

I want to asynchronously download image, so first user sees a low resolution image, and higher resolution version is downloaded in the background. I have tried the following.
<html>
<head>
<script>
window.addEventListener('load', function () {
var kuvaEl = document.getElementById('kuva');
var r_src = kuvaEl.getAttribute('r-src');
var a_src = kuvaEl.getAttribute('a-src');
kuvaEl.setAttribute('src', r_src);
kuvaEl.setAttribute('src', a_src);
});
</script>
</head>
<body>
<img id="kuva" src="http://www.viikonloppu.com/wp-content/uploads/2014/04/lotoflaughters.com_-619x428.jpg?c3bc1b"
a-src="https://www.manitowoccranes.com/~/media/Images/news/2014/Potain-China-hi-res.jpg"
r-src="http://fuzyll.com/images/2016/angel_oak_panorama.jpg" />
</body>
</html>
But the problem is r_src download is aborted when src is change second time. I want to download both of these images in parallel, and show the r_src first (only if it downloads faster than a_src), and when the *a_src *is ready, show the a_src.
Also, is it possible to download these a_src and r_src images to the browser cache before the src is actually changed? Ideally I would like the the src change to either retrieve the image from the cache or join the pending download for that url.
I can also use jQuery. IE7 must support the implementation.
You just need to use javascript or jquery and load two version of the same image. the first will be your low res, but you will download a high res inside an hidden img tag.
When the download is complete, you just hide / delete the low res image and show the high res.
This link show some test and few way to do it. And it should support ie7 Load a low-res background image first, then a high-res one
You can use interlaced progressive JPEG format.
This method is the preferred method for handling high quality images and has been implemented by so many websites.the idea is that the compression of the image is made in such away that the when you send the image the receiver gets the image in finer and finer detail has the sending of the data progressed.
if you dont want to use the abouve technique
Have the low quality image in the src of the image. once the whole page loaded successfully,change the low quality image with high quality image
<img id="target-image" src="low-quality.jpg" data-src="high-quality.jpg" />
$(window).load(function(){
var imgSrc = $('#target-image').data('src');
$('#target-image').attr('src',imgSrc);
});
You should put your low res as default src. Then use JS to download the high res version and on download completion, change image src.
Also, good practice is to use data-* for custom attributes
If your really want a parallel download, you should replace "load" event for the "DOMContentLoaded" event. However, this will extend the time your user has to wait until page is ready. Your should keep the load event to prioritize critical assets loading (scripts and stylesheets)
window.addEventListener('load', function() {
// get all images
let images = document.getElementsByClassName("toHighRes");
// for each images, do the background loading
for (let i = 0; i < images.length; i++) {
InitHighResLoading(images[i]);
}
});
function InitHighResLoading(image) {
let hrSrc = image.dataset["hr"];
let img = new Image();
img.onload = () => {
// callback when image is loaded
image.src = hrSrc;
}
// launch download
img.src = hrSrc;
}
img {
/* only for code snippet */
max-height: 300px;
}
<img class="toHighRes"
data-hr="https://www.manitowoccranes.com/~/media/Images/news/2014/Potain-China-hi-res.jpg"
src="http://fuzyll.com/images/2016/angel_oak_panorama.jpg" />

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

rewrite image source URL with javascript

I stuck when experimenting with blogger thumbnails. I don't want to use blogger default thumbnails since the size just 72px, it's very small. So, I found a method by rewriting the URL of the image source (the image hosted by google blogger service).
For example, I have an image in this URL http://4.bp.blogspot.com/-XfeUAQMRZnk/VBw8Gv0tZvI/AAAAAAAAAXM/DnmxYqUROVc/s1600/home%2Bthumbs.jpg, the image will loaded with max-width 1600px, indicated by the /s1600/ in the URL. I want to load the image at 300px width, then the URL will be http://4.bp.blogspot.com/-XfeUAQMRZnk/VBw8Gv0tZvI/AAAAAAAAAXM/DnmxYqUROVc/s300/home%2Bthumbs.jpg. Also, the image served in HTTP protocol by default, but it's possible to served in HTTPS just by adding https:// as the protocol.
This is my thumbnail markup:
<div class="thumbnail">
<a class="thumbTooltip" href="#" title="Flat Design Sample">
<img alt="Flat Design Sample" src="http://4.bp.blogspot.com/-XfeUAQMRZnk/VBw8Gv0tZvI/AAAAAAAAAXM/DnmxYqUROVc/s1600/home%2Bthumbs.jpg">
</a>
</div>
The question is, how I can rewrite the default image URL by using javascript method? I want to force the image served in HTTPS by rewriting http:// to https://, and served in 300px width by rewriting s1600 to s300. The final URL will look like this: https://4.bp.blogspot.com/-XfeUAQMRZnk/VBw8Gv0tZvI/AAAAAAAAAXM/DnmxYqUROVc/s300/home%2Bthumbs.jpg
The code is inside an window.onload to ensure that all elements are there. Then in the url-string the first replace() changes the protocol. The second uses a regular expression to find the segment where the size is defined and changes it to s300. It will work even when the images comes from another directory.
window.onload = function() {
var img = document.querySelector('.thumbnail img');
img.src = img.src.replace('http', 'https').replace(/\/s\d+(?=\/)/, '/s300');
};
Instead of the window.onload wrap you also can put the code in <script>-tags just before </body>.
Simple replacement of a token.
function getThumbnailUrl (element)
{
$url = element.href.split("/");
$url[7] = "s300";
return $url.join("/");
}

how to remove delay in image loading in html?

I create a web page and put an img tag on this page. the img.src is the url of the image from the network IP camera. It works but the stream I get have delays. I understand this delay is because I load the image and loading image takes some time. my question is how can I minize these delay. I do the following;
<script language="Javascript">
x = document.getElementById("stream");
intervalID = setInterval(LoadImage, 0);
function LoadImage()
{
x = document.getElementById("stream");
x.src = "http://IP:PORT/jpg/image.jpg";
}
</script>
<img id="stream"
width="640" height="480"
alt="Press reload if no video displays"
border="0" style="cursor:crosshair; border:medium; border:thick" />
<button type="button" id="btnStartLive" onclick="onStartLiveBtnClick()">Start Live</button>
I've just found your question in the unanswered section and decided to give it a go. The following script creates an internal <img> tag (with new Image()), assigns the necessary attributes, then sets an onload "event handler" attribute, which checks when the image loaded. When that function is called, the #stream is replaced by the new internal image tag.
In case the #stream is not directly inside the body tag (i.e. inside another element like a <div>), edit streamParentElement to point to the image's parent element.
I added a ?nocache query parameter to the string, because while I was testing the code, I found out that the image tag was changing but the visible image stayed the same. I also added a loadDelay, because the images on my client were loading too fast, and it got to the point where it crashed my browser. I advise you to not lower that value below 50. Live demonstration of this code here
<script language="Javascript">
var streamParentElement = document.body, loadDelay = 200;
setTimeout(MakeImage,1);
function MakeImage(){
var img = new Image();
img.src = "http://IP:PORT/jpg/image.jpg?nocahce="+new Date().getTime()+Math.random();
img.width = 640;
img.height = 480;
img.style.border = 0;
img.style.cursor = 'crosshair';
img.id = 'stream';
img.onload = function(){
var stream = document.getElementById("stream");
streamParentElement.insertBefore(img,stream);
stream.outerHTML = '';
setTimeout(MakeImage, loadDelay);
};
}
</script>
<img id="stream" alt="Press reload if no video displays" />
create your html page. eg:
<html>
<head>
<title>
Some Page
</title>
</link rel="stylesheet" href="path to your css file"/>
<script type="text/javascript" src="path to you javasctipt file"></script>
</head>
<body>
<h1 onClick="javascript:someFunction()">
Click here
</h1>
</body>
</html>
you can then create many other "someFunction" functions. They all just reference the AJAX function.this is just to make typing a little less...
The easiest ajax way:
var path;
var div;
var xmlhttp = new XMLHttpRequest();
function someFunction()
{
path = "path to another html file";
div = "the name of the div tag's content you want to change eg. content";
AJAX(path, div);
}
function AJAX(path, div)
{
xmlhttp.open("GET", path, false);
xmlhttp.send();
if (xmlhttp.readyState == 4)
{
document.getElementById(div).innerHTML = xmlhttp.responseText;
}
}
now just include the image in the html file.
ajax allows you to change just the content of the div you gave it, without reloading the whole page.
I would try putting your images into photoshop and making the resolution 72 or less. Also if you save the images as a GIFs they should be much smaller.
maybe handle the image loading in an outside script that runs faster than a web page refreshes, then embed it? like a "videoloader.js" so that it can load separately and not have to wait on the html page to load.
<script src="videoloader.js"></script>
you could also convert the images shown on the fly into lesser quality jpgs using javascript
see if this helps:
Load lower quality image if higher one inst available

FBJS setStyle( {backgroundImage}) not working?

i am trying to add some images to my facebook tab-app via FBJS.
The Problem:
I can't see the images and I don't know why.
The FBJS code
url = "http://www.domain.de/image.gif";
myImg = document.createElement('img');
myImg.setStyle( {backgroundImage: 'url('+url+')' });
document.getElementById('wrapper').appendChild(myImg);
The rendered html
<img style="background-image: url("http://www.domain.de/image.gif";);">
Try modifying your code like this and specify the src attribute of the image:
url = "http://www.domain.de/image.gif";
myImg = document.createElement('img');
myImg.setSrc(url);
document.getElementById('wrapper').appendChild(myImg);
You're really thing to set the background image of an img element? That seems...odd. Are you sure you don't just want to do a normal img element (Sarfraz may have you covered there if so) or specify the background image of the wrapper element? E.g.:
url = "http://www.domain.de/image.gif";
document.getElementById('wrapper').setStyle( {backgroundImage: 'url('+url+')' });
I've marked this CW because I've never done any FBJS, so could be talking through my hat. :-) If it helps, it helps.

Categories