Web Frontend Develope, Design, Music, Life——Stay Hungry, Stay Foolish~

iframe高度自适应(跨域)

a里面有iframe b

关于同域的情况,可以通过document.frames['b'].height = document.frames['b'].contentWindow.document.scrollHeight来设定,对于跨域的情况有很多种解决方法:

1.通过window.name

2.通过location.hash

都需要通过创建一个和a页面同域的代理文件c,第一种情况创建一个与a同域的iframe c,在目的iframe b设置其window.name为数据,然后删除此iframe c,就可以得到iframe b里的高度数据;第二种情况,创建一个与a同域的irame c,c中通过parent.parent可以访问到a页面,或a页面通过frames['b'].frames['c'].location.hash可以访问到c的location hash,高度通过hash来传就可以了。

实例的代码有时间续。

Javascript函数缓存(Memoizer)

在计算机领域,Memoization是一个通过避免重复计算先前的执行结果用来加速电脑程序的优化技巧。

其实很简单,就是通过把每次执行的结果放到一个Cache中去,下次执行的时候看Cache里是否有,如果有就直接返回,可以大大提高Javascript的效率。

我看的一个比较好的Javascript Memozier是这样的,通过递归和闭包的方法来实现:

// memoize: memoization方法
// func: 被memoized的函数
// context: 执行环境
// Note: 参数必须用直接简单的,对象的话要转换成string的,因为cache里的key都是用字符串来表示的。
function memoize (func, context) {
    function memoizeArg (argPos) {
        var cache = {};
        return function () {
            if (argPos == 0) {
                if (!(arguments[argPos] in cache)) {
                    cache[arguments[argPos]] = func.apply(context, arguments);
                }
                return cache[arguments[argPos]];
            }
            else {
                if (!(arguments[argPos] in cache)) {
                    cache[arguments[argPos]] = memoizeArg(argPos - 1);
                }
                return cache[arguments[argPos]].apply(this, arguments);
            }
        }
    }
    var arity = func.arity || func.length;//func参数的长度,jscript中用length属性,其它的用arity属性
    return memoizeArg(arity - 1);
}

另外Realazy同学也写了一个简单的Memoization http://realazy.org/blog/2008/04/22/javascript-memoization/
返回顶部