等待所有图像加载jquery ajax / jquery pjax

时间:2011-06-18 03:10:17

标签: jquery ajax pjax

这是我试图做的事情的一小部分

$.pjax = function( options ) {
  var $container = $(options.container),
      success = options.success || $.noop

  // We don't want to let anyone override our success handler.
  delete options.success

  // We can't persist $objects using the history API so we must use
  // a String selector. Bail if we got anything else.
  if ( typeof options.container !== 'string' )
    throw "pjax container must be a string selector!"

  var defaults = {
    timeout: 650,
    push: true,
    replace: false,
    // We want the browser to maintain two separate internal caches: one for
    // pjax'd partial page loads and one for normal page loads. Without
    // adding this secret parameter, some browsers will often confuse the two.
    data: { _pjax: true },
    type: 'GET',
    dataType: 'html',
    beforeSend: function(xhr){
      $container.trigger('start.pjax')
      xhr.setRequestHeader('X-PJAX', 'true')
    },
    error: function(){
      window.location = options.url
    },
    complete: function(){


$container.trigger('end.pjax')
},
success: function(data){
  // If we got no data or an entire web page, go directly
  // to the page and let normal error handling happen.
  if ( !$.trim(data) || /<html/i.test(data) )
    return window.location = options.url

  // Make it happen.
  // i think im not getting it right.
  $(window).load(
      function() {
          $container.html(data)
      }
  );

Official way to ask jQuery wait for all images to load before executing something类似,但在jquery ajax请求之后。

正如您在底部// Make it happen看到的那样,我试图在html(数据)中的所有图片准备投放后返回html(数据),我们可以做吗?不知何故?

谢谢!

Adam Ramadhan

1 个答案:

答案 0 :(得分:0)

我相信在浏览器开始加载任何图像之前,您必须将加载的HTML插入到DOM中。您应该能够将其插入隐藏的(display:none)div中,并在该隐藏的div上设置.load()回调。

This plugin改进了.load()事件,以便在图像加载时更加一致地触发。