开发者

jquery: simple image preloader + onload

开发者 https://www.devze.com 2023-01-20 17:36 出处:网络
i\'m trying to make a simple image-preloader for just ONE image. it should load an image and - if finished - fire an event for displaying it.

i'm trying to make a simple image-preloader for just ONE image. it should load an image and - if finished - fire an event for displaying it. what's the simplest method to do this?

i only know the pure javascript solution, like document.createElement("img") - but what's the best method using jquer开发者_运维技巧y?

what i've got so far (but dunno if it's the optimal way):

var img = $("<img src='/images/myPic.jpg'>");
img.bind("load", function(){alert("loaded!")});

thanks


If I understand correctly I would write the image in the template or master page or whatever using with a css attribute and then an event in jquery to display it.

<img id="preloader" src="/myimg.jpg" style="display:none;" />


$("#some-element").ready(function(){
      $("#preloader").show();
});


I've never had to do this with jQuery as I either do it manually in JS:

var img = new Image();
img.onLoad = function() {alert("Image has been loaded!");};
img.src = "path/to/img.ext";

Or, if I'm already using jQuery for the project, I'll just use Thickbox. If you look at its source, it has something similar to the above.

To display it, have a pre-defined div in your source file that is initially set to display: none;, then use JS to set its content to the image and change it to be visible. You can see an example of this at pcgalore.com, the rotating quote banner uses it.


I would use jquery's .on() method and attach it to the selector:

<img id="preLoader" src="/images/myPic.jpg" alt="My Pic" style="display: none;" />

$('#preLoader').on('load', function () {
    $(this).fadeIn();
});
0

精彩评论

暂无评论...
验证码 换一张
取 消