php广告加载类用法实例
本文实例讲述了php广告加载类的用法,非常实用。分享给大家供大家参考。具体方法如下:
该php广告加载类,支持异步与同步加载。需要使用Jquery实现。
ADLoader.class.php类文件如下:
<?php
/**广告加载管理类
*Date:2013-08-04
*Author:fdipzone
*Ver:1.0
*
*Func:
*publicload加载广告集合
*publicsetConfig广告配置
*privategetAds根据channel创建广告集合
*privategenZoneIdzoneidbase64_encode处理
*privategenHtml生成广告html
*privatecheckBrowser检查是否需要同步加载的浏览器
*/
classADLoader{//classstart
privatestatic$_ads=array();//广告集合
privatestatic$_step=300;//广告加载间隔
privatestatic$_async=true;//是否异步加载
privatestatic$_config=array();//广告设置文件
privatestatic$_jsclass=null;//广告JSclass
/**加载广告集合
*@paramString$channel栏目,对应config文件
*@paramint$step广告加载间隔
*@paramboolean$async是否异步加载
*/
publicstaticfunctionload($channel='',$step='',$async=''){
if(isset($step)&&is_numeric($step)&&$step>0){
self::$_step=$step;
}
if(isset($async)&&is_bool($async)){
self::$_async=$async;
}
//判断浏览器,如IE强制使用同步加载
if(!self::checkBrowser()){
self::$_async=false;
}
self::getAds($channel);
self::genZoneId();
returnself::genHtml();
}
/**设置config
*@paramString$config广告配置
*@paramString$jsclassjsclass文件路径
*/
publicstaticfunctionsetConfig($config=array(),$jsclass=''){
self::$_config=$config;
self::$_jsclass=$jsclass;
}
/**根据channel创建广告集合
*@paramString$channel栏目
*/
privatestaticfunctiongetAds($channel=''){
$AD_Config=self::$_config;
if($AD_Config!=null){
self::$_ads=isset($AD_Config[$channel])?$AD_Config[$channel]:$AD_Config['default'];
}
}
/**zoneidbase64_encode处理*/
privatestaticfunctiongenZoneId(){
//同步加载广告不需要处理zoneid
if(!self::$_async){
return;
}
$ads=self::$_ads;
for($i=0,$len=count($ads);$i<$len;$i++){
if(isset($ads[$i]['zoneId'])){
$ads[$i]['zoneId']=base64_encode('varzoneid='.$ads[$i]['zoneId'].';');
}
}
self::$_ads=$ads;
}
/**生成广告html*/
privatestaticfunctiongenHtml(){
$ads=self::$_ads;
$html=array();
if(self::$_jsclass!=null&&$ads){
array_push($html,'<scripttype="text/javascript"src="'.self::$_jsclass.'"></script>');
//同步需要预先加载
if(!self::$_async){
foreach($adsas$ad){
array_push($html,'<divid="'.$ad['domId'].'_container"style="display:none">');
array_push($html,'<scripttype="text/javascript">');
array_push($html,'ADLoader.preload('.json_encode($ad).');');
array_push($html,'</script>');
array_push($html,'</div>');
}
}
array_push($html,'<scripttype="text/javascript">');
array_push($html,'varads='.json_encode($ads).';');
array_push($html,'$(document).ready(function(){ADLoader.load(ads,'.self::$_step.','.intval(self::$_async).');});');
array_push($html,'</script>');
}
returnimplode("\r\n",$html);
}
/**判断是否需要强制同步加载的浏览器*/
privatestaticfunctioncheckBrowser(){
$user_agent=$_SERVER['HTTP_USER_AGENT'];
if(strstr($user_agent,'MSIE')!=''){
returnfalse;
}
returntrue;
}
}//classend
?>
ADConfig.php文件如下:
<?php /**广告配置文件**/ returnarray( 'case_openx'=>array( array( 'type'=>'openx', 'domId'=>'ad_728x90', 'zoneId'=>452 ), array( 'type'=>'openx', 'domId'=>'ad_300x250', 'zoneId'=>449 ), array( 'type'=>'openx', 'domId'=>'ad_l2_300x250', 'zoneId'=>394 ), ), 'case_url'=>array( array( 'type'=>'url', 'domId'=>'ad_728x90', 'url'=>'adurl.php?zoneid=452' ), array( 'type'=>'url', 'domId'=>'ad_300x250', 'url'=>'adurl.php?zoneid=449' ), array( 'type'=>'url', 'domId'=>'ad_l2_300x250', 'url'=>'adurl.php?zoneid=394' ) ), 'case_sync_openx'=>array( array( 'type'=>'openx', 'domId'=>'ad_728x90', 'zoneId'=>452 ), array( 'type'=>'openx', 'domId'=>'ad_300x250', 'zoneId'=>449 ), array( 'type'=>'openx', 'domId'=>'ad_l2_300x250', 'zoneId'=>394 ), ), 'default'=>array( array( 'type'=>'openx', 'domId'=>'ad_728x90', 'zoneId'=>452 ), array( 'type'=>'openx', 'domId'=>'ad_300x250', 'zoneId'=>449 ), array( 'type'=>'openx', 'domId'=>'ad_l2_300x250', 'zoneId'=>394 ), ), ); ?>
ADLoader.js文件如下:
/**异步加载广告
*Date:2013-08-04
*Author:fdipzone
*Ver:1.0
*/
varADLoader=(function(){
var_ads=[],//广告集合
_step=300,//广告加载间隔
_async=true,//是否异步加载
_loaded=0;//已经加载的广告数
/**loadAd循环加载广告
*@paramintc第几个广告
*/
functionloadAD(c){
if(_loaded>=_ads.length){
return;
}
if($('#'+_ads[c].domId).length>0){//判断dom是否存在
if(_async){//异步执行
crapLoader.loadScript(getScript(_ads[c]),_ads[c].domId,{
success:function(){
completeAd();
}
});
}else{//将同步加载的广告显示
varad_container=$('#'+_ads[c].domId+'_container');
ad_container.find('embed').attr('wmode','transparent').end().find('object').each(function(k,v){
v.wmode='transparent';//将flash变透明
});
$('#'+_ads[c].domId)[0].appendChild(ad_container[0]);
ad_container.show();
completeAd();
}
}else{//dom不存在
completeAd();
}
}
/**加载完广告后处理*/
functioncompleteAd(){
_loaded++;
setTimeout(function(){
loadAD(_loaded);
},_step);
}
/**获取广告
*@paramArrayad广告参数
*/
functiongetScript(ad){
varret=null;
switch(ad.type){
case'openx'://openxcodead
ret='data:text/javascript;base64,'+ad.zoneId+'dmFyIG0zX3UgPSAobG9jYXRpb24ucHJvdG9jb2w9PSdodHRwczonPydodHRwczovL2Fkcy5ubWcuY29tLmhrL3d3dy9kZWxpdmVyeS9hanMucGhwJzonaHR0cDovL2Fkcy5ubWcuY29tLmhrL3d3dy9kZWxpdmVyeS9hanMucGhwJyk7CnZhciBtM19yID0gTWF0aC5mbG9vcihNYXRoLnJhbmRvbSgpKjk5OTk5OTk5OTk5KTsKaWYgKCFkb2N1bWVudC5NQVhfdXNlZCkgZG9jdW1lbnQuTUFYX3VzZWQgPSAnLCc7CmRvY3VtZW50LndyaXRlICgiPHNjciIrImlwdCB0eXBlPSd0ZXh0L2phdmFzY3JpcHQnIHNyYz0nIittM191KTsKZG9jdW1lbnQud3JpdGUgKCI/em9uZWlkPSIgKyB6b25laWQpOwpkb2N1bWVudC53cml0ZSAoJyZhbXA7Y2I9JyArIG0zX3IpOwppZiAoZG9jdW1lbnQuTUFYX3VzZWQgIT0gJywnKSBkb2N1bWVudC53cml0ZSAoIiZhbXA7ZXhjbHVkZT0iICsgZG9jdW1lbnQuTUFYX3VzZWQpOwpkb2N1bWVudC53cml0ZSAoZG9jdW1lbnQuY2hhcnNldCA/ICcmYW1wO2NoYXJzZXQ9Jytkb2N1bWVudC5jaGFyc2V0IDogKGRvY3VtZW50LmNoYXJhY3RlclNldCA/ICcmYW1wO2NoYXJzZXQ9Jytkb2N1bWVudC5jaGFyYWN0ZXJTZXQgOiAnJykpOwpkb2N1bWVudC53cml0ZSAoIiZhbXA7bG9jPSIgKyBlc2NhcGUod2luZG93LmxvY2F0aW9uKSk7CmlmIChkb2N1bWVudC5yZWZlcnJlcikgZG9jdW1lbnQud3JpdGUgKCImYW1wO3JlZmVyZXI9IiArIGVzY2FwZShkb2N1bWVudC5yZWZlcnJlcikpOwppZiAoZG9jdW1lbnQuY29udGV4dCkgZG9jdW1lbnQud3JpdGUgKCImY29udGV4dD0iICsgZXNjYXBlKGRvY3VtZW50LmNvbnRleHQpKTsKaWYgKGRvY3VtZW50Lm1tbV9mbykgZG9jdW1lbnQud3JpdGUgKCImYW1wO21tbV9mbz0xIik7CmRvY3VtZW50LndyaXRlICgiJz48XC9zY3IiKyJpcHQ+Iik7';
break;
case'url'://urlad
ret=ad.url;
break;
}
returnret;
}
/**同步加载广告
*@paramArrayad广告参数
*/
functionwriteAd(ad){
switch(ad.type){
case'openx':
varm3_u=(location.protocol=='https:'?'https://ads.nmg.com.hk/www/delivery/ajs.php':'http://ads.nmg.com.hk/www/delivery/ajs.php');
varm3_r=Math.floor(Math.random()*99999999999);
if(!document.MAX_used)document.MAX_used=',';
document.write("<scr"+"ipttype='text/javascript'src='"+m3_u);
document.write("?zoneid="+ad.zoneId);
document.write('&cb='+m3_r);
if(document.MAX_used!=',')document.write("&exclude="+document.MAX_used);
document.write(document.charset?'&charset='+document.charset:(document.characterSet?'&charset='+document.characterSet:''));
document.write("&loc="+escape(window.location));
if(document.referrer)document.write("&referer="+escape(document.referrer));
if(document.context)document.write("&context="+escape(document.context));
if(document.mmm_fo)document.write("&mmm_fo=1");
document.write("'><\/scr"+"ipt>");
break;
case'url':
document.write('<scripttype="text/javascript"src="'+ad.url+'"></script>');
break;
}
}
obj={
/**加载广告
*@paramArrayads广告集合
*@paramintstep广告加载间隔
*@parambooleanasynctrue:异步加载false:同步加载
*/
load:function(ads,step,async){
_ads=ads;
if(typeof(step)!='undefined'){
_step=step;
}
if(typeof(async)!='undefined'){
_async=async;
}
loadAD(_loaded);
},
/**预加载广告*/
preload:function(ad){
if($('#'+ad.domId).length>0){//判断dom是否存在
writeAd(ad);
}
}
}
returnobj;
}());
/*crapLoader*/
varcrapLoader=(function(){
varisHijacked=false,
queue=[],
inputBuffer=[],
writeBuffer={},
loading=0,
elementCache={},
returnedElements=[],
splitScriptsRegex=/(<script[\s\S]*?<\/script>)/gim,
globalOptions={
autoRelease:true,
parallel:true,
debug:false
},
defaultOptions={
charset:undefined,
success:undefined,
func:undefined,
src:undefined,
timeout:3000
},publ,
head=document.getElementsByTagName("head")[0]||document.documentElement,
support={
scriptOnloadTriggeredAccurately:false,
splitWithCapturingParentheses:("abc".split(/(b)/)[1]==="b")
};
functioncheckQueue(){
if(queue.length){
loadScript(queue.shift());
}elseif(loading===0&&globalOptions.autoRelease){
debug("Queueisempty.Auto-releasing.");
publ.release();
}
}
functioncheckWriteBuffer(obj){
varbuffer=writeBuffer[obj.domId],
returnedEl;
if(buffer&&buffer.length){
writeHtml(buffer.shift(),obj);
}else{
while(returnedElements.length>0){
returnedEl=returnedElements.pop();
varid=returnedEl.id;
varelInDoc=getElementById(id);
if(!elInDoc){continue;}
varparent=elInDoc.parentNode;
elInDoc.id=id+"__tmp";
parent.insertBefore(returnedEl,elInDoc);
parent.removeChild(elInDoc);
}
finished(obj);
}
}
functiondebug(message,obj){
if(!globalOptions.debug||!window.console){return;}
varobjExtra="";
if(obj){
objExtra="#"+obj.domId+"";
vardepth=obj.depth;
while(depth--){objExtra+="";}
}
console.log("crapLoader"+objExtra+message);
}
functionextend(t,s){
vark;
if(!s){returnt;}
for(kins){
t[k]=s[k];
}
returnt;
}
functionfinished(obj){
if(obj.success&&typeofobj.success==="function"){
obj.success.call(document.getElementById(obj.domId));
}
checkQueue();
}
functionflush(obj){
vardomId=obj.domId,
outputFromScript,
htmlPartArray;
outputFromScript=stripNoScript(inputBuffer.join(""));
inputBuffer=[];
htmlPartArray=separateScriptsFromHtml(outputFromScript);
if(!writeBuffer[domId]){
writeBuffer[domId]=htmlPartArray;
}else{
Array.prototype.unshift.apply(writeBuffer[domId],htmlPartArray);
}
checkWriteBuffer(obj);
}
functiongetCachedElById(domId){
returnelementCache[domId]||(elementCache[domId]=document.getElementById(domId));
}
functiongetElementById(domId){
return(publ.orgGetElementById.call?
publ.orgGetElementById.call(document,domId):
publ.orgGetElementById(domId));
}
functiongetElementByIdReplacement(domId){
varel=getElementById(domId),
html,frag,div,found;
functiontraverseForElById(domId,el){
varchildren=el.children,i,l,child;
if(children&&children.length){
for(i=0,l=children.length;i<l;i++){
child=children[i];
if(child.id&&child.id===domId){returnchild;}
if(child.children&&child.children.length){
vartmp=traverseForElById(domId,child);
if(tmp)returntmp;
}
}
}
}
functionsearchForAlreadyReturnedEl(domId){
vari,l,returnedEl;
for(i=0,l=returnedElements.length;i<l;i++){
returnedEl=returnedElements[i];
if(returnedEl.id===domId){returnreturnedEl;}
}
}
if(el){returnel;}
if(returnedElements.length){
found=searchForAlreadyReturnedEl(domId);
if(found){
returnfound;
}
}
if(inputBuffer.length){
html=inputBuffer.join("");
frag=document.createDocumentFragment();
div=document.createElement("div");
div.innerHTML=html;
frag.appendChild(div);
found=traverseForElById(domId,div);
if(found){
returnedElements.push(found);
}
returnfound;
}
}
varglobalEval=(function(){
return(window.execScript?function(code,language){
window.execScript(code,language||"JavaScript");
}:function(code,language){
if(language&&!/^javascript/i.test(language)){return;}
window.eval.call(window,code);
});
}());
functionisScript(html){
returnhtml.toLowerCase().indexOf("<script")===0;
}
functionrunFunc(obj){
obj.func();
obj.depth++;
flush(obj);
}
functionloadScript(obj){
loading++;
//asyncloadingcodefromjQuery
varscript=document.createElement("script");
if(obj.type){script.type=obj.type;}
if(obj.charset){script.charset=obj.charset;}
if(obj.language){script.language=obj.language;}
logScript(obj);
vardone=false;
//Attachhandlersforallbrowsers
script.onload=script.onreadystatechange=function(){
loading--;
script.loaded=true;
if(!done&&(!this.readyState||
this.readyState==="loaded"||this.readyState==="complete")){
done=true;
script.onload=script.onreadystatechange=null;
debug("onload"+obj.src,obj);
flush(obj);
}
};
script.loaded=false;
script.src=obj.src;
obj.depth++;
//UseinsertBeforeinsteadofappendChildtocircumventanIE6bug.
//Thisariseswhenabasenodeisused(#2709and#4378).
head.insertBefore(script,head.firstChild);
setTimeout(function(){
if(!script.loaded){thrownewError("SCRIPTNOTLOADED:"+script.src);}
},obj.timeout);
}
functionlogScript(obj,code,lang){
debug((code?
"Inline"+lang+":"+code.replace("\n","").substr(0,30)+"...":
"Inject"+obj.src),obj);
}
functionseparateScriptsFromHtml(htmlStr){
returnsplit(htmlStr,splitScriptsRegex);
}
functionsplit(str,regexp){
varmatch,prevIndex=0,tmp,result=[],i,l;
if(support.splitWithCapturingParentheses){
tmp=str.split(regexp);
}else{
//CrossbrowsersplittechniquefromStevenLevithan
//http://blog.stevenlevithan.com/archives/cross-browser-split
tmp=[];
while(match=regexp.exec(str)){
if(match.index>prevIndex){
result.push(str.slice(prevIndex,match.index));
}
if(match.length>1&&match.index<str.length){
Array.prototype.push.apply(tmp,match.slice(1));
}
prevIndex=regexp.lastIndex;
}
if(prevIndex<str.length){
tmp.push(str.slice(prevIndex));
}
}
for(i=0,l=tmp.length;i<l;i=i+1){
if(tmp[i]!==""){result.push(tmp[i]);}
}
returnresult;
}
functionstripNoScript(html){
returnhtml.replace(/<noscript>[\s\S]*?<\/noscript>/ig,"");
}
functiontrim(str){
if(!str){returnstr;}
returnstr.replace(/^\s*|\s*$/gi,"");
}
functionwriteHtml(html,obj){
if(isScript(html)){
vardummy=document.createElement("div");
dummy.innerHTML="dummy<div>"+html+"</div>";//trickforIE
varscript=dummy.children[0].children[0];
varlang=script.getAttribute("language")||"javascript";
if(script.src){
obj.src=script.src;
obj.charset=script.charset;
obj.language=lang;
obj.type=script.type;
loadScript(obj);
}else{
varcode=trim(script.text);
if(code){
logScript(obj,code,lang);
globalEval(code,lang);
}
flush(obj);
}
}else{
varcontainer=getCachedElById(obj.domId);
if(!container){
thrownewError("crapLoader:Unabletoinjecthtml.Elementwithid'"+obj.domId+"'doesnotexist");
}
html=trim(html);//newlinebefore<object>causeweirdeffectsinIE
if(html){
container.innerHTML+=html;
}
checkWriteBuffer(obj);
}
}
functionwriteReplacement(str){
inputBuffer.push(str);
debug("write:"+str);
}
functionopenReplacement(){
//document.open()justreturnsthedocumentwhencalledfromablockingscript:
//http://www.whatwg.org/specs/web-apps/current-work/#dom-document-open
returndocument;
}
functioncloseReplacement(){
//document.close()doesnothingwhencalledfromablockingscript:
//http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
}
publ={
hijack:function(options){
if(isHijacked){return;}
isHijacked=true;
extend(globalOptions,options);
if(globalOptions.parallel&&!support.scriptOnloadTriggeredAccurately){
globalOptions.parallel=false;
debug("Browsersonloadisnotreliable.Disablingparallelloading.");
}
document.write=document.writeln=writeReplacement;
document.open=openReplacement;
document.close=closeReplacement;
document.getElementById=getElementByIdReplacement;
},
release:function(){
if(!isHijacked){return;}
isHijacked=false;
document.write=this.orgWrite;
document.writeln=this.orgWriteLn;
document.open=this.orgOpen;
document.close=this.orgClose;
document.getElementById=this.orgGetElementById;
elementCache={};
},
handle:function(options){
if(!isHijacked){
debug("Notinhijackedmode.Auto-hijacking.");
this.hijack();
}
vardefaultOptsCopy=extend({},defaultOptions);
varobj=extend(defaultOptsCopy,options);
obj.depth=0;
if(!obj.domId){
obj.domId="craploader_"+newDate().getTime();
varspan=document.createElement("span");
span.id=obj.domId;
document.body.appendChild(span);
}
if(options.func){
runFunc(obj);
return;
}
if(globalOptions.parallel){
setTimeout(function(){
loadScript(obj);
},1);
}else{
queue.push(obj);
setTimeout(function(){
if(loading===0){
checkQueue();
}
},1);
}
},
loadScript:function(src,domId,options){
if(typeofdomId!=="string"){
options=domId;
domId=undefined;
}
this.handle(extend({
src:src,
domId:domId
},options));
},
runFunc:function(func,domId,options){
if(typeofdomId!=="string"){
options=domId;
domId=undefined;
}
this.handle(extend({
domId:domId,
func:func
},options));
},
orgGetElementById:document.getElementById,
orgWrite:document.write,
orgWriteLn:document.writeln,
orgOpen:document.open,
orgClose:document.close,
_olt:1,
_oltCallback:function(){
support.scriptOnloadTriggeredAccurately=(publ._olt===2);
}
};
returnpubl;
}());
demo.php示例程序如下:
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="content-type"content="text/html;charset=utf-8">
<title>ADLoader</title>
<styletype="text/css">
.banner1{margin:10px;border:1pxsolid#CCCCCC;width:728px;height:90px;}
.banner2{margin:10px;border:1pxsolid#CCCCCC;width:300px;height:250px;}
</style>
<scripttype="text/javascript"src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<divclass="banner1"id="ad_728x90"></div>
<divclass="banner2"id="ad_300x250"></div>
<divclass="banner2"id="ad_l2_300x250"></div>
<?php
functionshowAD($channel='',$step='',$async=''){
include('ADLoader.class.php');
$ad_config=include('ADConfig.php');
ADLoader::setConfig($ad_config,'ADLoader.js');
returnADLoader::load($channel,$step,$async);
}
echoshowAD('case_openx');//异步加载
//echoshowAD('case_url');//url方式异步加载
//echoshowAD('case_sync_openx',300,false);//同步加载
?>
</body>
</html>
adurl.php文件如下:
<?php
$zoneid=isset($_GET['zoneid'])?intval($_GET['zoneid']):0;
if($zoneid){
?>
varzoneid=<?=$zoneid?>;
varm3_u=(location.protocol=='https:'?'https://ads.nmg.com.hk/www/delivery/ajs.php':'http://ads.nmg.com.hk/www/delivery/ajs.php');
varm3_r=Math.floor(Math.random()*99999999999);
if(!document.MAX_used)document.MAX_used=',';
document.write("<scr"+"ipttype='text/javascript'src='"+m3_u);
document.write("?zoneid="+zoneid);
document.write('&cb='+m3_r);
if(document.MAX_used!=',')document.write("&exclude="+document.MAX_used);
document.write(document.charset?'&charset='+document.charset:(document.characterSet?'&charset='+document.characterSet:''));
document.write("&loc="+escape(window.location));
if(document.referrer)document.write("&referer="+escape(document.referrer));
if(document.context)document.write("&context="+escape(document.context));
if(document.mmm_fo)document.write("&mmm_fo=1");
document.write("'><\/scr"+"ipt>");
<?}?>
本文所述完整实例源码点击此处本站下载。
希望本文所述对大家的php程序设计有所帮助。