开发者

How to optimize my javascript code?

I just created a javscript plugin that waits for all the images. The following is my current source code.

$.fn.waitAllImages = function(options){

    var defaults = {
        speed: 900
    }

    var options = $.extend(defaults,options);


    var preloader = $("<div/>");
    preloader.addClass('moonsPreloader');
    preloader.attr("id",options.id+"-preloader");


    var hideWrapper = $("<div/>");
    hideWrapper.attr("id",options.id+"-hide-wrapper");
    hideWrapper.css("disp开发者_StackOverflow中文版lay","none");

    $(this).wrapAll(hideWrapper);

    $("body").append(preloader);

    $(window).bind('load',function(){
        $("#"+options.id+"-preloader").remove();
        $("#"+options.id+"-hide-wrapper").eq(0).fadeIn(options.speed);
    });


}

It works, but I have a concern.

As you see, load callback access options.id. $.fn.waitAllImages and load callback are two different functions. Does that mean load callback prevents javascript garage collector to clean options.id variable?


Garbage collection details are implementation-specific, but yes your load function holds a reference to the options variable, so it will be available for the lifetime of that function.

This is rarely a problem in practice, but if it bothers you, you can pass a copy of the values you need instead:

$(window).bind('load', { id: options.id, speed: options.speed }, function(event){
    $("#"+event.data.id+"-preloader").remove();
    $("#"+event.data.id+"-hide-wrapper").eq(0).fadeIn(event.data.speed);
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜