[翻译]High Performance JavaScript(004)
XMLHttpRequest Script Injection XHR脚本注入
Another approach to nonblocking scripts is to retrieve the JavaScript code using an XMLHttpRequest (XHR) object and then inject the script into the page. This technique involves creating an XHR object, downloading the JavaScript file, then injecting the JavaScript code into the page using a dynamic <script> element. Here's a simple example:
另一个以非阻塞方式获得脚本的方法是使用XMLHttpRequest(XHR)对象将脚本注入到页面中。此技术首先创建一个XHR对象,然后下载JavaScript文件,接着用一个动态<script>元素将JavaScript代码注入页面。下面是一个简单的例子:
var xhr = new XMLHttpRequest();
xhr.open("get", "file1.js", true);
xhr.onreadystatechange = function(){
if (xhr.readyState == 4){
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
var script = document.createElement_x("script");
script.type = "text/javascript";
script.text = xhr.responseText;
document.body.appendChild(script);
}
}
};
xhr.send(null);
This code sends a GET request for the file file1.js. The onreadystatechange event handler checks for a readyState of 4 and then verifies that the HTTP status code is valid (anything in the 200 range means a valid response, and 304 means a cached response). If a valid response has been received, then a new <script> element is created and its text property is assigned to the responseText received from the server. Doing so essentially creates a <script> element with inline code. Once the new <script> element is added to the document, the code is executed and is ready to use.
此代码向服务器发送一个获取file1.js文件的GET请求。onreadystatechange事件处理函数检查readyState是不是4,然后检查HTTP状态码是不是有效(2XX表示有
相关文档:
看书的时候遇到这样一个问题,程序代码如下
var ob = function(){
var obj = this;
function fn1(){
alert( obj === window );//false
alert( this === window );//ture
}
this.fn2 = function() {
fn1();
}
}
当时很不明白fn1里面第二个alert的结果,为 ......
这个随笔其实是为了感谢清风笑给的一个提示,不仅仅是告诉我怎么判断数组,更让我有了认真读一读 《javascript权威指南》的想法。
比较和拷贝其实是一回事,代码如下:
//
//Compare object function
//
function Compare(fobj,sobj)
{
var ftype = typ ......
作用域 Scope
Javascript 中的函数属于词法作用域,也就是说函数在它被定义时的作用域中运行而不是在被执行时的作用域内运行。这是犀牛书上的说法。但“定义时”和“执行(被调用)时”这两个东西有些人搞不清楚。简单来说,一个函数A在“定义时”就是 function A(){} 这个语句执行的时候就 ......
Grouping Scripts 成组脚本
Since each <script> tag blocks the page from rendering during initial download, it's helpful to limit the total number of <script> tags contained in the page. This applies to both inline scripts as well as those in external files. Every time ......
Dynamic Script Elements 动态脚本元素
The Document Object Model (DOM) allows you to dynamically create almost any part of an HTML document using JavaScript. At its root, the <script> element isn't any different than any other element on a page: references can be retrie ......