jQuery .load(function) 同步化

5

如何同步使用jQuery的load函数最佳方式。

我需要加载一张图片,但在该图片加载完成之前无法执行下一行代码。

我可以循环一个变量直到加载完成,但想知道是否有更好的方法。

var img = jQuery('<img src="' + url + '"/>').load(function () {                 

            });  
  //Run code here once img load has comlpeted.                                              

1
这里有你需要的内容:http://stackoverflow.com/questions/5364166/how-to-load-page-synchronously-using-jquery - tymeJV
6个回答

10
您也可以使用回调函数来获得同步行为 -
var result = $('#main-container').load( 'html/Welcomeform.html', 
                function () {
                     if($("textarea").find("#mail-id")){
                        $("textarea#mail-id").val(email_id);
                     }
                     } );   

7
据我所知,load事件除非图像已经被缓存(在某些浏览器中),否则总是以异步方式触发。唯一可靠的解决方案是像您所做的那样将代码放在回调函数中。然而,为了确保load处理程序在所有浏览器中始终被触发,即使图像已被缓存,请确保在设置src属性之前添加处理程序。

1
var img = jQuery('<img src="' + url + '"/>').load(runner);  
function runner() {
    //run code here once image is loaded
}

0

load() 中的回调函数将在屏幕的基本元素(实际的 HTML)被检索后触发,但不会等待图像完成,您可以使用它来使其等待。

$('#holder').load(function() { 
var imgcount = $('#holder img').length; 
$('#holder img').load(function(){ 
imgcount--; 
if (imgcount == 0) { 
/* now they're all loaded, let's display them! */ 
} 
}); 
});

0

我来到这里寻找类似的解决方案。从阅读中得知,使用.load是不可能实现的,你需要使用AJAX请求,正如问题评论所指出的那样。

在我的情况下,我需要加载一个HTML文件,并添加一个过渡效果来改变内容。即使我在load回调内部显示内容,过渡后旧内容仍然会在新内容之前显示。

var main = $("#main");
    main.load("about.html", displaySection);

function displaySection () {
   main.show('blind');
}

我的解决办法是在一个延迟时间为200的超时函数中运行显示已加载内容的转换。

var main = $("#main");
    main.load("about.html", displaySection);

function displaySection () {
    setTimeout(function() {
        main.show('blind');
    }, 200);
}

问题可能出在连接速度太慢,新页面需要超过200毫秒加载完成,但在这种情况下,我想知道回调函数是否会稍后启动。我不明白为什么没有超时设置就不能正常工作,感觉有些不雅观,但这解决了我的问题...以防其他人没有考虑到这种可能性。


0

因此,这可以通过 Promise 来管理。正如您可能知道的那样,您可以使用 await 运算符等待(顾名思义) Promise 被解决。因此,我们可以将 load() 方法转换为 Promise。

async function loadAsPromise(element, src) {
    var resolveFunction;
    const loadPromise = new Promise(function(resolve, _) {
        resolveFunction = resolve;
    });

    $(element).load(src, function () {
        console.log("SOLVED");
        resolveFunction();
    });

    return loadPromise;
}

你可以像这样使用你的函数:

await loadAsPromise(element, 'fileName');

// your other code

所以你的“其他代码”只有在 Promise 解决时才会执行,而这发生在加载完成时。我希望你会觉得这很有帮助!

如果您想了解更多关于如何解决 Promise 的信息,可以查看这个链接(我从中获得了灵感):

在 Promise 构造函数范围之外解决 JavaScript Promise


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接