主流JS框架中DOMReady事件的实现

2010-08-31 08:58:03.0

在实际应用中,我们经常会遇到这样的场景,当页面加载完成后去做一些事情:绑定事件、DOM操作某些结点等。原来比较常用的是window的onload 事件,而该事件的实际效果是:当页面解析/DOM树建立完成,并完成了诸如图片、脚本、样式表甚至是iframe中所有资源的下载后才触发的。这对于很多 实际的应用而言有点太“迟”了,比较影响用户体验。为了解决这个问题,FF中便增加了一个DOMContentLoaded方法,与onload相比,该 方法触发的时间更早,它是在页面的DOM内容加载完成后即触发,而无需等待其他资源的加载。Webkit引擎从版本525(Webkit nightly 1/2008:525+)开始也引入了该事件,Opera中也包含该方法。到目前为止主流的IE仍然没有要添加的意思。虽然IE下没有,但总是有解决办法 的,下文对比了一下几大主流框架对于该事件的兼容性版本实现方案,涉及的框架包括:

jQuery绑定事件的命名空间详解

2010-08-23 10:41:40.0

以前写过一篇

jQuery的事件绑定命名空间

说句实话,我现在回头去看下自己的这篇文章,我都看不懂,今日碰巧在网上看到一篇介绍jQuery的时间绑定命名空间的文章

jQuery

改造jQuery lazyLoad插件

2010-07-30 13:01:16.0

最近前端数据延迟加载(lazyload)技术很流行...

淘宝,新浪网都有使用延迟加载技术,

这样做的目的可以使得一些未在本屏幕显示的图片随着滚动条的滚动进行延迟显示。

好处显而易见,可以减少客户端对服务器端图片的Http请求,减轻服务器的压力,

对于长篇并且大批量的图片的网页效果非常明显

可惜淘宝网的延迟加载是基于YUI写的。。

 

ajax请求中高效率的获取XMLHttpRequest

2010-07-24 16:13:25.0

现在一直都是用jquery的ajax,对于原生js的ajax的原理 只能看懂....却不会写,翻开保存的网络资料,刚好找到司徒的一篇高效的获取XMLHttpRequest,剔除了原文中他自己框架中的代码。。。

本文仅记录ajax原理中的xmlhttprequest对象的创建.....

首先是W3C标准的XMLHttpRequest对象,微软从IE7开始也支持XMLHttpRequest对象,so我们在支持W3C标准的现代浏览器中(包括 IE 7)只需要

js通过classname来获取元素

2010-07-21 12:10:16.0

原生JS有3种方式来获取元素:

  1. getElementById('id')
  2. getElementsByName('name')
  3. getElementsByTagName('tag')

getElementById是获取元素最快的方式,但我们不能给每个HTML元素都加以ID吧,所以我们需要一个很方便的通过classname来获取元素:

function getElementsByClassName(className,tagName){
var ele=[],all=document.getElementsByTagName(tagName||"*");
for(var i=0;i<all.length;i++){
if(all[i].className==className){
ele[ele.length]=all[i];
}
}
return ele;
}
console.log(getElementsByClassName("entry"));
console.log(getElementsByClassName("entry","div"));

Array数组的each方法

2010-07-20 16:10:44.0

在jQuery中有个很方便的each方法来遍历数组,Firefox中的Array也有each方法,这里我们自己实现一个array的each方法

Array.prototype.each = function( callback ){ 
for( var i = 0 ,j = this.length ; i < j ; i++ ){ 
    callback.call( this, this[i], i ); 
      }    
   } 

js框架中类继承的比较

2010-07-13 09:24:16.0

首先我们来看下jQuery之父john resig的实现方法:

jq之父写的类继承方式的特点是:

  • 有私有变量
  • 可以写在一个构造函数中
  • 可以多级继承,可以有多个父类(需要某种特定格式)
  • 继承基于prototype,且不会执行父类的构造函数
  • 保持了父类的函数链,可以在子类中用this._super简单调用
  • instanceof 对子类、父类都生效

这是目前为止我看到的最好的方法。除了定义了一个全局变量Class外

// Inspired by base2 and Prototype
(function(){
var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
// The base Class implementation (does nothing)
this.Class = function(){};
// Create a new Class that inherits from this class
Class.extend = function(prop) {
var _super = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
// The dummy class constructor
function Class() {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.constructor = Class;
// And make this class extendable
Class.extend = arguments.callee;
return Class;
};
})();

javascript替换url中的参数

2010-07-09 11:47:22.0

有时候需要通过js来替换url中的参数,我以前发过一篇关于js解析url的文章,我们在这基础上加上替换url参数的功能

//分析url
function parseURL(url) {
var a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':', ''),
host: a.hostname,
port: a.port,
query: a.search,
params: (function () {
var ret = {},
seg = a.search.replace(/^\?/, '').split('&'),
len = seg.length, i = 0, s;
for (; i < len; i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
hash: a.hash.replace('#', ''),
path: a.pathname.replace(/^([^\/])/, '/$1'),
relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
segments: a.pathname.replace(/^\//, '').split('/')
};
}
//替换myUrl中的同名参数值
function replaceUrlParams(myUrl, newParams) {
/*
for (var x in myUrl.params) {
for (var y in newParams) {
if (x.toLowerCase() == y.toLowerCase()) {
myUrl.params[x] = newParams[y];
}
}
}
*/
for (var x in newParams) {
var hasInMyUrlParams = false;
for (var y in myUrl.params) {
if (x.toLowerCase() == y.toLowerCase()) {
myUrl.params[y] = newParams[x];
hasInMyUrlParams = true;
break;
}
}
//原来没有的参数则追加
if (!hasInMyUrlParams) {
myUrl.params[x] = newParams[x];
}
}
var _result = myUrl.protocol + "://" + myUrl.host + ":" + myUrl.port + myUrl.path + "?";
for (var p in myUrl.params) {
_result += (p + "=" + myUrl.params[p] + "&");
}
if (_result.substr(_result.length - 1) == "&") {
_result = _result.substr(0, _result.length - 1);
}
if (myUrl.hash != "") {
_result += "#" + myUrl.hash;
}
return _result;
}
//辅助输出
function w(str) {
document.write(str + "<br>");
}
var myURL = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top');
w("myUrl.file = " + myURL.file)     // = 'index.html'
w("myUrl.hash = " + myURL.hash)     // = 'top'
w("myUrl.host = " + myURL.host)     // = 'abc.com'
w("myUrl.query = " + myURL.query)    // = '?id=255&m=hello'
w("myUrl.params = " + myURL.params)   // = Object = { id: 255, m: hello }
w("myUrl.path = " + myURL.path)     // = '/dir/index.html'
w("myUrl.segments = " + myURL.segments) // = Array = ['dir', 'index.html']
w("myUrl.port = " + myURL.port)     // = '8080'
w("myUrl.protocol = " + myURL.protocol) // = 'http'
w("myUrl.source = " + myURL.source)   // = 'http://abc.com:8080/dir/index.html?id=255&m=hello#top'
var _newUrl = replaceUrlParams(myURL, { id: 101, m: "World", page: 1,"page":2 });
w("<br>新url为:")
w(_newUrl); //http://abc.com:8080/dir/index.html?id=101&m=World&page=2#top

兼容各浏览器的event以及srcElement,fromElement,toElement属性

2010-07-06 23:23:18.0

在 IE 中获取事件对象很容易,直接用 event,event.srcElement,event.fromElement,event.toElement 就行了。在 FireFox 中获得触发事件的元素可以用 event.target,但其他两个 fromElement 和 toElement ,属于IE的专属方法,如果要兼容IE的用法就要费些周折了

虽然IE经常我行我素,但无可否认,在这里,srcElement,fromElement,toElement.这三个方法很好用!

所以,为了保持一致的使用方式,也为了保持原有的使用习惯,我们来为非IE浏览器也加上这三个方法,我们通过继承prototype来实现这三个函数

用cssText来批量修改style

2010-06-21 16:24:17.0

js中给一个html元素设置css属性,可以通过style属性来操作

var head= document.getElementById("head");
head.style.width = "200px";
head.style.height = "70px";
head.style.display = "block";

如果要设置的样式很多,这样写太罗嗦了,而且会造成浏览器渲染的reflow,懒人总是用懒办法,不是说程序员要越懒越好嘛,还有就是 懒人推动了科技的发展