ajax外部文件,在使用Ajax加载外部文件,为什么在提示之后才加载完成?

原因是jQuery load方法的实现是先填充DOM再调用回调函数。

下面是jQuery load方法的源码:

jQuery.fn.load = function( url, params, callback ) {

if ( typeof url !== "string" && _load ) {

return _load.apply( this, arguments );

}

var selector, response, type,

self = this,

off = url.indexOf(" ");

if ( off >= 0 ) {

selector = url.slice( off, url.length );

url = url.slice( 0, off );

}

// If it's a function

if ( jQuery.isFunction( params ) ) {

// We assume that it's the callback

callback = params;

params = undefined;

// Otherwise, build a param string

} else if ( params && typeof params === "object" ) {

type = "POST";

}

// If we have elements to modify, make the request

if ( self.length > 0 ) {

jQuery.ajax({

url: url,

// if "type" variable is undefined, then "GET" method will be used

type: type,

dataType: "html",

data: params

}).done(function( responseText ) {

// Save response for use in complete callback

response = arguments;

self.html( selector ?

// If a selector was specified, locate the right elements in a dummy div

// Exclude scripts to avoid IE 'Permission Denied' errors

jQuery("

").append( jQuery.parseHTML( responseText ) ).find( selector ) :

// Otherwise use the full result

responseText );

}).complete( callback && function( jqXHR, status ) {

self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );

});

}

return this;

};

你传入的文件路径text/text最终仍然是通过ajax去获取的,获取了文件内容后,在done方法里使用.html()把内容放到了DOM元素中,然后调用complete函数,而传入参数中的回调函数callback是在complete函数中调用的。

所以,是先调用的self.html(data),渲染好了DOM,然后再调用回调函数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值