youku的js脚本的工具函数和初始化方法

       定义日志输出函数

(function(){
	if(window['console']){ return; }
	window['console'] = {
		 log: function(){}
		,clear: function(){}
		,debug: function(){}
		,error: function(){}
		,info: function(){}
		,count: function(){}
		,time: function(){}
		,trace: function(){}
		,warn: function(){}
	}
})();

       定义全局的方法,实现加载cdn的响应的地址

(function(){
    var url = 'Bad url, watch browser console error.',
        Local = window.Local,
        err = function(msg){ if(console && console.error){  console.error('[cdn function error] '+ msg + '.'); } },
        cdn = function(path, type){
            //path rule
            if(path.charAt(0) != '/'){ err('@param path: relative to root start by /'); return url; }
            //global block
            if(!Local){ err('@see BETA-18932: template funciton {nova->globaJS}'); return url; }
            var key = 'RELEASE_TAG', version = Local[key];
            //version define
            if(!version){ err('@see local: ' + key + ' not defined'); return url; }
            //server define
            key = type.toUpperCase() + 'SERVER', server = Local[key];
            if(!server){ err('@see local: ' + key + ' not defined.'); return url; }
            //bad server define
            if(!server.match(/^(http|https)/)){ err('@see local: ' + key + ' is server, add protocol'); return url; }
            if(server.match(/\/$/)){ err('@see local: ' + key + ' is server, not ending by \/'); return url; }
            url = server+ '/' +  version + path;
            return url;
        };
        window.cdn_jsurl = function(path){ return cdn(path, 'js'); };
        window.cdn_cssurl = function(path){ return cdn(path, 'css'); };
        window.cdn_imgurl = function(path){ return cdn(path, 'img'); };
})();

        全站监听连接事件

//监听全站的链接点击事件,检查是否存在data-from属性,并添加from参数至href属性中
(function(o){
	if(!o) {return false;}
	if(!o.Event) {return false;}
	var checkFromDomain = function(href){
		var domain = ["youku.com/v_show/","youku.com/show_page/","youku.com/u/U"];
		for(var i=0,length=domain.length; i<length; i++){
			if(href.indexOf(domain[i]) !== -1) {
				return true;
			}
		}
	}
	o.nova_init_hook_data_from = function(){
		o.Event.observe(document, "click",  function(ev){
			if(!ev) ev = o.event;
			var target = ev.target || ev.srcElement;
			if(!target) {return;}
			if(target.tagName != 'A' && target.parentNode) {
				target = target.parentNode;
			}
			if(target.tagName == 'A') {
				var data_from = target.getAttribute("data-from");
				var from = data_from || window.pvDataFrom;
				var href = target.getAttribute("href");
				if(from && from != '') {
					if(href && href.indexOf('http') === 0 && href.indexOf('?from') === -1 && href.indexOf('&from') === -1 && checkFromDomain(href)) {
						from = encodeURIComponent(from);
						if(href.indexOf('?') !== -1){
							target.setAttribute("href", href+'&from='+from);
						}else{
							target.setAttribute("href", href+'?from='+from);
						}
					}
				}
			}
		});
	}
 })(window);

        生成时间戳+6位随机数的字符串

var getPvid = function(len){
		var randchar=["0","1","2","3","4","5","6","7","8","9",
			"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
			"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
					];
		var i=0;
		var r="";
		var d=new Date();
		for (i=0;i<len;i++){
				         var index=parseInt(Math.random()*Math.pow(10,6))%randchar.length;
						          r+=randchar[index];
		}
		return d.getTime()+r;
}

        jsonp异步调用方法

	var jsonp = function(src, callback){
		if(typeof(arguments[0]) != 'string'){ return; }
		var callback = typeof(arguments[1]) == 'function' ? callback : function(){};
		var head = document.getElementsByTagName('HEAD')[0];
		var script = document.createElement('SCRIPT');
		script.type = 'text/javascript';
		script.src = src;
		head.appendChild(script);
		if(!/*@cc_on!@*/0) {
			script.onload = function(){ callback(); this.parentNode.removeChild(this); }
		}else{
			script.onreadystatechange = function () {
				if (this.readyState == 'loaded' || this.readyState == 'complete') {
					callback();
					this.parentNode.removeChild(this);
				}
			}
		}
	}

        过滤空字符串

function ltrim(s){ return s.replace( /^(\s*| *)/, ""); }
function rtrim(s){ return s.replace( /(\s*| *)$/, ""); }
function trim(s){ return ltrim(rtrim(s));}

        判断是否为空值

/**
 * 判断变量是否空值
 * undefined, null, '', false, 0, [], {} 均返回true,否则返回false
 */
function empty(v){
    switch (typeof v){
        case 'undefined' : return true;
        case 'string'    : if(trim(v).length == 0) return true; break;
        case 'boolean'   : if(!v) return true; break;
        case 'number'    : if(0 === v) return true; break;
        case 'object'    :
            if(null === v) return true;
            if(undefined !== v.length && v.length==0) return true;
            for(var k in v){return false;} return true;
            break;
    }
    return false;
}

        根据cookie判断是否已经登录

var islogin = function(){
	var username = '';
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if(c.indexOf('yktk=') == 0){
			var u_info = decode64(decodeURIComponent(c).split("|")[3]);
			if(u_info.indexOf(",") > -1 && u_info.indexOf("nn:") > -1 && u_info.indexOf("id:") > -1){
				 username = u_info.split(",")[1].split(":")[1];
				 if(username != '') break;
			}
		}
	}

	return (username == '') ? false : true;
}

        判断是否为email

function isEmail(mail){
	return(new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]{1,4}$/).test(mail));
}



function U8_16(_1) {
    var i, len, c;
    var char2, char3;
    var ary = [];
    len = _1.length;
    i = 0;
    while (i < len) {
        c = _1.charCodeAt(i++);
        switch (c >> 4) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
            // 0xxxxxxx
            ary.push(_1.charAt(i - 1));
            break;
        case 12:
        case 13:
            // 110x xxxx   10xx xxxx
            char2 = _1.charCodeAt(i++);
            ary.push(String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)));
            break;
        case 14:
            // 1110 xxxx 10xx xxxx 10xx xxxx
            char2 = _1.charCodeAt(i++);
            char3 = _1.charCodeAt(i++);
            ary.push(String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)));
            break;
        }
    }
    return ary.join('');
}
function decode64(_1) {
    if(!_1) return '';
    var _2 = "ABCDEFGHIJKLMNOP"+"QRSTUVWXYZabcdef"+"ghijklmnopqrstuv"+"wxyz0123456789+/"+"=";
    var _3 = "";
    var _4, _5, _6;
    var _7, _8, _9, _a;
    var i = 0;
    _1 = _1.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    do {
        _7 = _2.indexOf(_1.charAt(i++));
        _8 = _2.indexOf(_1.charAt(i++));
        _9 = _2.indexOf(_1.charAt(i++));
        _a = _2.indexOf(_1.charAt(i++));
        _4 = (_7 << 2) | (_8 >> 4);
        _5 = ((_8 & 15) << 4) | (_9 >> 2);
        _6 = ((_9 & 3) << 6) | _a;
        _3 = _3 + String.fromCharCode(_4);
        if (_9 != 64) {
            _3 = _3 + String.fromCharCode(_5);
        }
        if (_a != 64) {
            _3 = _3 + String.fromCharCode(_6);
        }
    } while (i < _1.length);
    return U8_16(_3);
}
function encode64(str)
{
    if(!str) return '';
    str = str.toString();
    var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var base64DecodeChars = new Array(
       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
       -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
       52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
       -1, 0,   1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
       15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
       -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
       41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1
    );
    var out, i, len;
    var c1, c2, c3;
    len = str.length;
    i = 0;
    out = "";
    while(i < len) {
        c1 = str.charCodeAt(i++) & 0xff;
        if(i == len)
        {
            out += base64EncodeChars.charAt(c1 >> 2);
            out += base64EncodeChars.charAt((c1 & 0x3) << 4);
            out += "==";
            break;
        }
        c2 = str.charCodeAt(i++);
        if(i == len)
        {
            out += base64EncodeChars.charAt(c1 >> 2);
            out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
            out += base64EncodeChars.charAt((c2 & 0xF) << 2);
            out += "=";
            break;
        }
        c3 = str.charCodeAt(i++);
        out += base64EncodeChars.charAt(c1 >> 2);
        out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
        out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6));
        out += base64EncodeChars.charAt(c3 & 0x3F);
    }
    return out;
}
function encodeUid(uid)
{
    if(!uid) return '';
    if(uid << 2 > 0){
        var enUid = 'U' + encode64(uid << 2);
    }else{
        //uid超过限制
        var enUid = 'U' + encode64(uid * 4);
    }
    return enUid;
}

 

posted @ 2016-01-27 09:05  wala-wo  阅读(669)  评论(0编辑  收藏  举报