Load Image from javascript

妖精的绣舞 提交于 2019-11-27 09:26:27

you can just append another hidden img element and swap them in onload event.

Or use single image element and use javascript like:

var _img = document.getElementById('id1');
var newImg = new Image;
newImg.onload = function() {
    _img.src = this.src;
}
newImg.src = 'http://whatever';

this code should preload the image and show it when it's ready

Sorry guys.

You can't rely on the image load event to fire but you can kind of rely on it in some situations and fallback to a maximum load time allowed. In this case, 10 seconds. I wrote this and it lives on production code for when people want to link images on a form post.

function loadImg(options, callback) {
  var seconds = 0,
  maxSeconds = 10,
  complete = false,
  done = false;

  if (options.maxSeconds) {
    maxSeconds = options.maxSeconds;
  }

  function tryImage() {
    if (done) { return; }
    if (seconds >= maxSeconds) {
      callback({ err: 'timeout' });
      done = true;
      return;
    }
    if (complete && img.complete) {
      if (img.width && img.height) {
        callback({ img: img });
        done = true;
        return;
      }
      callback({ err: '404' });
      done = true;
      return;
    } else if (img.complete) {
      complete = true;
    }
    seconds++;
    callback.tryImage = setTimeout(tryImage, 1000);
  }
  var img = new Image();
  img.onload = tryImage();
  img.src = options.src;
  tryImage();
}

use like so:

loadImage({ src : 'http://somewebsite.com/image.png', maxSeconds : 10 }, function(status) {
  if(status.err) {
    // handle error
    return;
  }
  // you got the img within status.img
}); 

Try it on JSFiddle.net

http://jsfiddle.net/2Cgyg/6/

<span>
    <img id="my_image" src="#" />
</span>

<span class="spanloader">

    <span>set Loading Image Image</span>


</span>

<input type="button" id="btnnext" value="Next" />


<script type="text/javascript">

    $('#btnnext').click(function () {
        $(".spanloader").hide();
        $("#my_image").attr("src", "1.jpg");
    });

</script>

If you are loading the image via AJAX you could use a callback to check if the image is loaded and do the hiding and src attribute assigning. Something like this:

$.ajax({ 
  url: [image source],
  success: function() {
  // Do the hiding here and the attribute setting
  }
});

For more reading refer to this JQuery AJAX

Use a new image object each time you want to load a picture :

var image = new Image();
image.onload = function () {
    document.getElementById('id1').setAttribute('src', this.src);
};
image.src = 'http://path/to/image';

Try this.You have some symbols in $imageUrl

<img id="id1" src="$imageUrl" onload="javascript:showImage();">

You can try this:

<img id="id1" src="url/to/file.png" onload="showImage()">

function showImage() {
 $('#id1').attr('src', 'new/file/link.png');
}

Also, try to remove the ~, that is just the operator, that is needed for Server-Side (for example ASP.NET) you don't need it in JS.

This way, you can change the attribute for the image.

Here is the fiddle: http://jsfiddle.net/afzaal_ahmad_zeeshan/8H4MC/

See this tutorial: Loading images with native JavaScript and handling of events for showing loading spinners

It tells you how to load images with native JavaScript and how to handle events for showing loading spinners. Basically, you create a new Image(); and handle the event correctly then. That should work in all browsers, even in IE7 (maybe even below IE7, but I did not test that...)

this worked for me though... i wanted to display the image after the pencil icon is being clicked... and i wanted it seamless.. and this was my approach..

i created an input[file] element and made it hidden,

<input type="file" id="upl" style="display:none"/>

this input-file's click event will be trigged by the getImage function.

<a href="javascript:;" onclick="getImage()"/>
    <img src="/assets/pen.png"/>
</a>

<script>
     function getImage(){
       $('#upl').click();
     }
</script>

this is done while listening to the change event of the input-file element with ID of #upl.

   $(document).ready(function(){
     
       $('#upl').bind('change', function(evt){
         
		  var preview = $('#logodiv').find('img');
		  var file    = evt.target.files[0];
		  var reader  = new FileReader();
		
		  reader.onloadend = function () {
			$('#logodiv > img')
				.prop('src',reader.result)  //set the scr prop.
				.prop('width', 216);  //set the width of the image
				.prop('height',200);  //set the height of the image
		  }
		
		  if (file) {
			reader.readAsDataURL(file);
		  } else {
			preview.src = "";
		  }
		
	   });

   })

and BOOM!!! - it WORKS....

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!