jQuery to prepend URL in img src attribute - javascript

I just need a jQuery snippet to do the prepend in img src , i.e
<img src='/img/picture1.jpg' />
The code snippet jQuery is to prepend this url
http://cdn.something.com/
so after the snippet jQuery, it becomes like
<img src='http://cdn.something.com/img/picture1.jpg' />
Any help is greatly appreciated.
so far I wrote something like
$().ready(function(){
var cdn ='http://cdn.something.com';
$('img').attrib('src', cdn);
});
However it is replaced the src rather than pre

it's not really jQuery related, anyway you could do it with .attr()what is that?:
$('img').attr('src', function(index, src) {
return 'http://cdn.something.com' + src;
});
This would affect all of your <img> nodes in your markup and replace the src.
Anyway, I'm not so sure that this is a great idea. At the time theDOMready event fires, a browser might already have tried to access the old source attribute. If you must do this in Javascript, it's probably a better idea to store the path info within a custom data attribute so a browser is not tempted to load the image. This could look like:
HTML
<img src='' data-path='/img/picture1.jpg' />
JS
$(function() {
$('img').attr('src', function(index, src) {
return 'http://cdn.something.com' + this.getAttribute('data-path');
});
});
This should do it. You could replace this.getAttribute() by $(this).data('path') since jQuery parses those data attributes into it's "node" data hash. But this would create another jQuery object, which really is unecessary at this point.

This should work:
$.ready(function() {
$('img').each(function() {
$(this).attr('src', cdn + $(this).attr('src'));
});
});
However I'm not sure it is the good solution for using a CDN, as the browser will have already tried to load the images from your server at the time the script will be called.
You should do this on the server side instead.

Depending what your specific problem is, you might be able to sort out this problem with a base tag, but I assume you will only want this on images, but changing the src once the page has loaded will make the images reload? IF the images don't exist in the current location you will need to change the src attribute before the page is loaded (server side).

Related

Is there a way to prevent img get requests from occurring using css or js?

If I can only use css and/or javascript, is there a way I can prevent a get request to an image from happening?
like this:
<img src="A.png"/>
img {
src:none;
}
And this will prevent the GET request to A.png when the page loads.
Does anyone know if this is possible?
Thanks
I feel like this should work for what you're looking for:
<script>
$(document).ready(function () {
$("img").attr("src", "");
});
</script>
It should replace the src attributes in all <img> tags.
You could also remove the src attribute with $("img").removeAttr("src").
Something similar in javascript would be:
<script>
document.addEventListener("DOMContentLoaded", function (event) {
var images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
images[i].setAttribute("src", "");
}
});
</script>
Like in jquery, you can use images[i].removeAttribute("src") to remove the html src attribute altogether.
Both of these scripts are at the bottom of my html.
I don't know if this is exactly what you're looking for, but hopefully this helps.
there is a javascript way:
giving no source to img initially (= not doing a request) and changing it source via javascript afterwards
if you want to enter the URLs of the image in the dom use data-src attribute as ISuthan Bala mentioned
<img data-src="my-image.png" />
Easy setting data-src to src via jQuery for example

Image load error only fires sometimes

I have a classified style website with 50-100 images per page all loading from different sources at once. Sometimes I get a 404 and I'm trying to handle that.
On each element containing images I have this script:
$el.find('img').one('error', function() {
console.log('broken image detected');
// Replace broken image with something else
}).each(function() {
if(this.complete || $(this).height() > 0){
$(this).load();
}
});
But it seems to fire at random, not picking up all 404 load errors - especially at the beginning of the page where literally none of the 404s are detected. Towards the end of the page it looks a bit better.
What's going on?
I should add, that this piece of JavaScript is not initialised BEFORE the entire DOM has finished loading, but I was under the impression that the .each part would cater for this?
Another idea would be to insert an inline load error detector:
<img src="http://example.com/image.jpg" onerror="window.errorHandler(this);">
But since my JavaScript is modular in design I would prefer to avoid this.
--- EDIT ---
I have solved this problem by inserting an inline script on the onerror handler. It's not super elegant, but it works because the listener is inserted at the same time as the src attribute. Also it is not dependent on jQuery.
I have done a slight work around in my front-end code to cater for this, by exposing a function to window.
All listeners to handle load or error events must be set BEFORE src property of img is setted.
You may implement lazy loading (i.e. insert <img> paths in a data attribute, put a fake pixel in the src attribute, and load the real images on DOM load with jQuery or JavaScript). You then shouldn't face any timing problems.
HTML:
<div id="gallery">
<img id="img1"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEAAAAALAAAAAABAAEAAAI="
data-src="imagethatgives404.gif"
width="200" height="200">
<img id="img2"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEAAAAALAAAAAABAAEAAAI="
data-src="http://static.jsbin.com/images/dave.min.svg"
width="200" height="200">
</div>
JS:
$(document).ready(function(){
var $el = $('#gallery');
$el.find('[data-src]')
.one('error', function(e) {
console.log(e.target.id + ' is broken');
// Replace broken image with something else
})
.each(function(index,element){
element.src = $(element).data('src');
});
});
The width and height on the <img> tags are used to show how dimensions are preserved.
Example here.

All images are loaded immediately with lazySizes plugin

I have a problem with my dynamic integration of Lazysizes plugin.
The fact is when I load the page (cache disable), all images of the src are loaded with the content.
After this, responsives images are lazy-loaded like I want.
My reflection :
I replace src attribute with a small image - but browser keeps to load original images before change src with this small image.
all images aren't display in the viewport when the page load because I use the padding ratio trick for each of them.
I tried to move my script in the header of the page, but nothing change.
Here my jquery script at the bottom of the page :
//lazy init
window.lazySizesConfig = window.lazySizesConfig || {};
lazySizesConfig.loadMode = 2;
lazySizesConfig.preloadAfterLoad = false;
$('img').addClass('lazyload');
$("img.lazyload").each(function() {
var src = $(this).attr('src').replace(/\.jpg$/i, "");
$(this).attr("data-sizes","auto");
$(this).attr("data-srcset",
src + '-240.jpg 240w,' +
src + '-360.jpg 360w,' +
src + '-480.jpg 480w, ' +
src + '-720.jpg 720w,' +
src + '-768.jpg 768w,' +
src + '-960.jpg 960w,' +
src + '-1280.jpg 1280w'
);
$(this).attr(
"src",
"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
);
});
I would like only responsive img is load when it is in the viewport.
any idea about my issue ?
thanks
The issue that you're having is caused by the fact, that you're using JavaScript, to set the data-sizes and data-srcset attributes.
lazySizes script expects you to specify all of that in your HTML output.
You have to make sure that jQuery will be loaded, and your script will be executed before lazysizes.js.
I can't guarantee for any of my advice below to be useful, because this script is not intended to be used like that. Still, if you really want to get it to work with jQuery script from your question, consider the following:
Remove async attribute from lazysizes <script> tag.
Set lazySizesConfig.preloadAfterLoad = true;
Run your script right after jQuery is loaded, doesn't matter where you put the script, just make sure it's executed before lazySizes and on $(document).ready().
Only if all above is done, the lazySizes should lazyload the images as expected.
You first need to specify data- atributtes.
Load HTML
Load jQuery and lazysizes.js
Get all data- and save in variable
Handle with it
I don't know if lazysizes.js have inside script some document ready function or some DOM change sniffer but I think you need a different approach.

Check if image can be loaded

I have a page with lots of images on it. My images are loaded from an external server. Usually this server it's loading tooooooooo slow, so my page stay loading until the external server starts running again. I want to put a blank image loaded from mine when the external server is down.
Is there any method to do something like this?
if ($("img").load=false) {
$("img").src="cantload.png";
}
Thank you so much, in advance!
If you're using jquery, and this piece of code happens before the binding of the image.
$("img").error(function() {
alert("Could not load image");
});
If not, then you could do something like this, which will always work, but will need to be on each image:
<img src="image.gif" onerror="alert('Could not load image.')">
If you want to activate this function after the elements are already in the DOM, you can use something like this.
var defaultSource = 'cantload.png';
$('img').each(function() {
var originalSource = $(this).attr('src');
$(this)
.attr('src', defaultSource)
.error(function(){
$(this).attr('src', defaultSource );
})
.attr('src', originalSource);
});
The above code would bind the inner function to handle the images' loading errors, and then make them all reload. The pictures that are already reloaded won't be actually reloaded again, but those with the errors will trigger the error handler and change the source attribute into cantload.png
jsFiddle Demo

jquery: exclude external resources from $(window).load()

I need to execute some scripts when all the resources on my domain and subdomain are loaded, so I did this:
$(window).load(function(){
// al my functions here...
}
The problem is that there are some external resources (not on my domain and subdomain) that sometimes take longer to load. Is there a way to exclude external resources from the load event?
EDIT:
I was hoping to do something like:
$(window).not(".idontcare").load(function()
but it's not working
I guess your external resources rely on a src attribute.
If so, in your page source code you could set the src attribute of the resources you don't want to wait for, not as src but as external_src.
Then you could easily do:
$(document).ready(function(){
$(window).load(function(){
// all your functions here...
});
$('[external_src]').each(function() {
var external_src = $(this).attr("external_src");
$(this).attr("src", external_src); // now it starts to load
$(this).removeAttr("external_src"); // keep your DOM clean
//Or just one line:
//$(this).attr("src", $(this).attr("external_src")).removeAttr("external_src");
});
});
This way the external resources should start loading as soon as just the DOM is ready, without waiting for the full window load.
I have almost same case. But in my case, I want to exclude all iframes that load content from another site (e.g. youtube, vimeo etc). Found a work around, so the scenario is hide 'src' attribute from all iframes when DOM is ready and put it back when window is finish load all another content.
(function($){
//DOM is ready
$(document).ready(function(){
var frame = $('iframe'),
frameSrc = new Array();
if( frame.length ){
$.each( frame, function(i, f){
frameSrc[i] = $(f).attr('src');
//remove the src attribute so window will ignore these iframes
$(f).attr('src', '');
});
//window finish load
$(window).on('load',function(){
$.each( frame, function(a, x){
//put the src attribute value back
$(x).attr('src', frameSrc[a]);
});
});
}
});
})(jQuery);
You can mark all elements in your site that load external resources by adding a special class, and change the iframe with $('.special_class') or something like that. I dont know if this is the best way but at least it works great in my side :D
Unfortunately, the window.onload event is very strict. As you might know it will fire when all und every resource was transfered and loaded, images, iframes, everything. So the quick answer to your question is no, there is no easy-to-use way to tell that event to ignore external resources, it makes no difference there.
You would need to handle that yourself, which could be a tricky thing according to how those resources are included and located. You might even need to manipulate the source code before it gets delivered to accomplish that.
As far as I know, there is an async - tag for script tags. You can your includes to:
<script src="script_path" async="true"></script>
This will not include them to the event.
maybe
$(document).ready(...)
instead of $(window).load() will help?
The document ready event executes already when the HTML-Document is loaded and the DOM is ready, even if all the graphics haven’t loaded yet.

Categories