I am newbie in web development and I'm having diffuculties making my web fast to load.
So I found this article and I implemented it. When visualizing my page I get that the image is not rendered at all. I get the following image:
<img src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="~/images/menunavegacion.png" />
<script>
function init() {
var imgDefer = document.getElementsByTagName('img');
for (var i = 0; i < imgDefer.length; i++) {
if (imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src', imgDefer[i].getAttribute('data-src'));
}
}
}
window.onload = init;
</script>
Also, I debug it with chrome and it seems to be switching correctly the real image with the fake one. However the web do not load the proper one.
What am I missing?
Thanks for any help
When you set the image path in the src
attribute to ~/images/img.png
, asp.net will resolve the path and generate an url relative to the application base url: /app_path/images/img.png
.
However the value of the attribute data-src
is not processed and looks like ~/images/img.png
(still prefixed by ~
). When you replace the value of src
by the value of data-src
, the browser resolve the path of the image as http://sample.com/~/images/img.png
. This path may not exists on your server and you get an error 404.
To sum up, you need to remove the ~
by using the method ResolveUrl
in WebForms or Url.Content
in MVC.