search
HomeWeb Front-endJS TutorialWhat are the knowledge points about img.onload?

What are the knowledge points about img.onload?

Sep 11, 2017 am 09:04 AM
WhichKnowledge points

Foreword:
When using onload, we always see various suggestions and different performances on different browsers. These experiences summarized by others are not achieved overnight, and they are all constantly hammered down. Code, constant trial and error, testing, and optimization can only climb out of the pit. Only when you encounter something you don't understand, try to figure it out, and type it a few times, the knowledge will be yours. My humble opinion~_~, no more nonsense...

Let’s take a look at the code first:

<body>
    <p class="box">
     <p> 1111</p>
    </p>
    <script type="text/javascript">    function loadImage(url, callback) {
        //创建一个Image对象,实现图片的预下载
        var img = new Image();
            img.src = url;
        console.log(&#39;----111----&#39;);        // 如果图片已经存在于浏览器缓存,直接调用回调函数
        if (img.complete) {
            callback(img);            // 直接返回,不用再处理onload事件
            return ;
        }
        img.onload = function() {
            console.log(&#39;----333----&#39;);             //图片下载完毕时异步调用callback函数
            callback(img);
        }
        console.log(&#39;----222----&#39;);
    }    function call(img) {
        // 有权访问另一个函数作用域内变量的函数都是闭包
        $(img).appendTo(&#39;.box&#39;);
    }
     loadImage(&#39;https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1504976397726&di=62045a300551dd62608d3e9423221c1f&imgtype=0&src=http%3A%2F%2Fp9.qhmsg.com%2Ft01ffd2fe0a1210db89.png&#39;,call);  
    //loadImage(&#39;./img/bird.png&#39;, call);
    </script>
[闭包概念讲解](http://www.cnblogs.com/wangfupeng1988/p/3994065.html)分析以上代码:
这个方法功能是ok的,但是有一些隐患。1  创建了一个临时匿名函数来作为图片的onload事件处理函数,形成了闭包。
相信大家都看到过ie下的内存泄漏模式的文章,其中有一个模式就是循环引用,而闭包就有保存外部运行环境的能力(依赖于作用域链的实现),所以 img.onload这个函数内部又保存了对img的引用,这样就形成了循环引用,导致内存泄漏。(这种模式的内存泄漏只存在低版本的ie6中,打过补丁 的ie6以及高版本的ie都解决了循环引用导致的内存泄漏问题)。
**这里有点类似于Object-c中block和self的Strong Reference cycle,即循环强引用,self引用了block,block中又用到了self,各自的引用计数器都为一,都强引用对方,不会销毁,造成内存泄漏。OC中就是把self变为weakSelf来解决,同理我们也要在这里有所作为。**2  只考虑了静态图片的加载,忽略了gif等动态图片,这些动态图片可能会多次触发onload。
要解决上面两个问题很简单,在img.onload中把img.onload=null;
代码如下:
img.onload = function () { 
   //图片下载完毕时异步调用callback函数。         
    img.onload = null;    
    callback(img);     
}; 
这样既能解决内存泄漏的问题,又能避免动态图片的事件多次触发问题。
在一些相关博文中,也有人注意到了要把img.onload 设置为null,只不过时机不对,大部分文章都是在callback运行以后,才将img.onload设置为null,这样虽然能解决循环引用的问题, 但是对于动态图片来说,如果callback运行比较耗时的话,还是有多次触发的隐患的。

隐患经过上面的修改后,就消除了,但是这个代码还有优化的余地:if (img.complete) { 
// 如果图片已经存在于浏览器缓存,直接调用回调函数     
      callback(img);     
      return; // 直接返回,不用再处理onload事件     }
经过对多个浏览器版本的测试,发现ie、opera下,当图片加载过一次以后,如果再有对该图片的请求时,由于浏览器已经缓存住这张图片了,不会再发起一次新的请求,而是直接从缓存中加载过来。
对于 firefox和safari,它们试图使这两种加载方式对用户透明,同样
会引起图片的onload事件(而ie和opera则忽略了这种同一性,不会引起图片的onload事件),因此上边的代码在它们里边不能得以实现效果。

确实,在ie,opera下,对于缓存图片的初始状态,与firefox和safari,chrome下是不一样的(有兴趣的话,可以在不同浏览器下,测试 一下在给img的src赋值缓存图片的url之前,img的complete状态),但是对onload事件的触发,却是一致的,不管是什么浏览器。产生这个问题的根本原 因在于,img的src赋值与 onload事件的绑定,顺序不对(在ie和opera下,先赋值src,再赋值onload,因为是缓存图片,就错过了onload事件的触发)。应该 先绑定onload事件,然后再给src赋值,代码如下:function loadImage(url, callback) {     
    var img = new Image(); //创建一个Image对象,实现图片的预下载     
    img.onload = function(){
        img.onload = null;
        callback(img);
    }
    img.src = url; 
}
这样内存泄漏,动态图片的加载问题都得到了解决,而且也以统一的方式,实现了callback的调用。

The above is the detailed content of What are the knowledge points about img.onload?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software