(function(d) { 
    var iframe = d.body.appendChild(d.createElement('iframe')), 
    doc = iframe.contentWindow.document;     // style the iframe with some CSS 
    iframe.style.cssText = "position:absolute;width:200px;height:100px;left:0px;";     doc.open().write('<body onload="' + 'var d = document;d.getElementsByTagName(\'head\')[0].' + 'appendChild(d.createElement(\'script\')).src' + '=\'\/path\/to\/file\'">');     doc.close(); //iframe onload event happens 
})(document); 请问(function(d) {...})(document);  什么意思?该函数什么时候执行?

解决方案 »

  1.   

    这段话,是直接“调用这个函数” 类似于这种:  (function(a){document.write(a);})(3)输出就是3,就是自动调用这个函数
      

  2.   

    谢谢1楼,还有个问题,这段代码老是报 'body'为空或不是对象,这个问题该怎么解决?谢谢!
      

  3.   


    因为document是全局变量。他这样做是将全局变量传进函数里面,就变成局部变量doc了,每次访问的时候都减少了访问作用域链,提高了性能
    你说body为空是因为document没准备好的时候你就调用了,你将此代码用
    window.onload = function(){
       //代码
    }执行
    或者放到body下面执行
    <body>
    </body>
    <script>
    //代码
    </script>