javascript同步执行 [英] javascript synchronous execution

查看:43
本文介绍了javascript同步执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 javascript 新手并尝试使用滑块.我的问题类似于以下问题jquery .attr() 带回调?.如果流是同步的,不应该延迟到源完全加载而不是显示旧图像

I am new to javascript and trying on a slider.My problem is similar to the below question jquery .attr() with callback?. If the flow is synchronous, shouldnt the display be delayed till the source is fully loaded rather than showing the old image

$('.container').fadeOut(100, function(){
     console.log("before");
     $('.container > img').attr('src', 'image src');
     $('.container').show();
     console.log("after");
 });

在加载新图像之前,我可以在控制台中看到两个日志.. 任何人都可以解释一下......如果问题很幼稚,请原谅我试图掌握这个概念..

I could see both the logs in the console before the new image gets loaded.. Can anyone pls explain...Pls pardon if the question is naive I am trying to get hold of the concept..

推荐答案

javascript 是同步的,但是问题是设置 src 属性和显示图片不一样.设置 src 后,您将调度浏览器开始加载图像,然后继续执行脚本.如果您希望在加载图像后执行代码,则必须将调用附加到图像的 onload 事件.

The javascript is synchronous, but the problem is that setting the src attribute is not the same as displaying the image. Once you set the src, you dispatch the browser to start loading the image, then the execution of your script continues. If you want code to execute after the image has been loaded, you'll have to attach the call to the image's onload event.

在 jQuery 中使用加载函数:

In jQuery use the load function:

$('.container > img').attr('src', 'image src').load(function(){
   // Stuff to do after the image has been loaded
});

这篇关于javascript同步执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆