我正在使用jquery get
将html加载到我的内容div上。我加载的HTML包含一些图像,我发现我在javascript中进行的自定义高度计算并不是很好,因为在loadHTML
返回时图像已完全加载。
var loadHTML = function(){
return $.get("javascripts/templates/" + templateType + ".html", function(text) {
$("#content").html(text);
});
};
有没有办法只能在所有图像加载后从loadHTML
返回?我试着致电并返回load
,但这不起作用
var loadHTML = function() {
return $.get("javascripts/templates/" + templateType + ".html", function(text) {
var content = $("#content").html(text);
return $('img', content).load();
})
};
另外,我在我的应用程序的其他部分使用Q promises,因此可以使用它修复我的问题。
即。 loadHTML.then(loadImages).then(doOtherStuff);
答案 0 :(得分:5)
您可以尝试使用下面的自定义延迟对象
var loadHTML = function () {
var deferred = $.Deferred();
$.get("javascripts/templates/" + templateType + ".html", function (html) {
var $html = $(html),
$imgs = $html.find('img'),
len = $imgs.length,
counter = 0;
$imgs.load(function () {
if (++counter == len) {
deferred.resolve();
}
});
$("#content").html($html);
});
return deferred.promise();
};
TD
var list = [];
for (var i = 0; i < 5; i++) {
list.push('<span><img src="//placehold.it/64&text=' + (i + 1) + '" /></span>');
}
var html = '<div>' + list.join('') + '</div>';
var loadHTML = function() {
var deferred = $.Deferred();
//using a timer to simulate ajax request
setTimeout(function() {
var $html = $(html),
$imgs = $html.find('img'),
len = $imgs.length,
counter = 0;
$imgs.load(function() {
if (++counter == len) {
deferred.resolve();
}
});
$("#content").html($html);
}, 500);
return deferred.promise();
};
loadHTML().done(function() {
$("#content").find('img').each(function() {
$(this).after(this.complete)
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content"></div>
答案 1 :(得分:0)
删除了我的另一个答案,因为它过于冗长。
您的代码无法正常工作的原因是您正在向服务器发出ajax请求,然后立即从该函数返回。该页面正在进行脚本编写,如果在该请求之前的工作与您的图像一起返回,则可能会完成最多。
您需要将返回移动到您知道在数据恢复之前不会处理的函数中的某个位置。您可以使用promises来执行此操作:
var jqxhr = $.get( "example.php", function() {
alert( "request sent, images are loading" );
// DON'T PUT YOUR RETURN HERE,
//YOU WANT TO CALL IT WHEN THE ABOVE IS DONE
})
.done(function() {
alert( "the info is loaded" );
//put your html insert here to make sure the
//data is fully loaded before you manipulate it
//you could also call htmlresize here but that would be nesting.
//That shit gets complicated. Just call it after this function returns on success.
return
})
.fail(function() {
alert( "error" );
// its good to handle errors
return
})
如果你不想占用你的整个页面加载来加载一些图像,你可以做一些简单的事情,比如将html resize和其他相关代码放在jqxhr.sucess回调上,以便在你的图像通过时读取其他代码。但这很复杂。