Jquery Image Src Change After Load
Solution 1:
Dont use .load which appends the content into the div. Use .get, amend the response then append into the dom.
$.get("test/page.html" ,"" ,function(data) {
$(data).find('img').each(function(intIndex) {
var src = $(this).attr("src");
var srcArray = src.split("/");
// change the src attribute
$(this).attr("src","test/" + srcArray[srcArray.length-1]);
}).appendTo('#content');
});
Solution 2:
As soon as you are creating <img>
tags - the browser will try to load them. Either through .load()
or $(data)
the browser is creating a IMG tag and setting src - effectively preloading them. The only way I could see getting around this is using a regexp like the one redsquare suggests. I saw a few improvements that could be made in the RE.
Here is an example allowing single and double quotes in src - I also scoped it to only search in img
tags, and case insensitively. And just to show a slightly different approach - used $.ajax instead of get/load
$.ajax({
url: 'test/page.html',
dataType: 'text',
success: function(data) {
$('#content').append(
data.replace(/<img([^>]*)\ssrc=['"](?:[^'"\/]*\/)*([^'"]+)['"]/gi, "<img$1 src='test/$2'")
);
}
});
Solution 3:
Can you try the following...I got some help with the regex as it really is not my skill..!
$.get("test/page.html" ,"" ,function(data) {
data.replace(/src='(?:[^'\/]*\/)*([^']+)'/g, "src='test/$1'")
$('#content').append( data );
});
Post a Comment for "Jquery Image Src Change After Load"