本文实例讲述了php广告加载类的用法,非常实用。分享给大家供大家参考。具体方法如下:
该php广告加载类,支持异步与同步加载。需要使用jquery实现。
adloader.class.php类文件如下:
<?php
/** 广告加载管理类
* date: 2013-08-04
* author: fdipzone
* ver: 1.0
*
* func:
* public load 加载广告集合
* public setconfig 广告配置
* private getads 根据channel创建广告集合
* private genzoneid zoneid base64_encode 处理
* private genhtml 生成广告html
* private checkbrowser 检查是否需要同步加载的浏览器
*/
class adloader{ // class start
private static $_ads = array(); // 广告集合
private static $_step = 300; // 广告加载间隔
private static $_async = true; // 是否异步加载
private static $_config = array(); // 广告设置文件
private static $_jsclass = null; // 广告js class
/** 加载广告集合
* @param string $channel 栏目,对应config文件
* @param int $step 广告加载间隔
* @param boolean $async 是否异步加载
*/
public static function load($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();
return self::genhtml();
}
/** 设置config
* @param string $config 广告配置
* @param string $jsclass js class文件路径
*/
public static function setconfig($config=array(), $jsclass=''){
self::$_config = $config;
self::$_jsclass = $jsclass;
}
/** 根据channel创建广告集合
* @param string $channel 栏目
*/
private static function getads($channel=''){
$ad_config = self::$_config;
if($ad_config!=null){
self::$_ads = isset($ad_config[$channel])? $ad_config[$channel] : $ad_config['default'];
}
}
/** zoneid base64_encode 处理 */
private static function genzoneid(){
// 同步加载广告不需要处理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('var zoneid='.$ads[$i]['zoneid'].';');
}
}
self::$_ads = $ads;
}
/** 生成广告html */
private static function genhtml(){
$ads = self::$_ads;
$html = array();
if(self::$_jsclass!=null && $ads){
array_push($html, '<script type="text/javascript" src="'.self::$_jsclass.'"></script>');
// 同步需要预先加载
if(!self::$_async){
foreach($ads as $ad){
array_push($html, '<div id="'.$ad['domid'].'_container" style="display:none">');
array_push($html, '<script type="text/javascript">');
array_push($html, 'adloader.preload('.json_encode($ad).');');
array_push($html, '</script>');
array_push($html, '</div>');
}
}
array_push($html, '<script type="text/javascript">');
array_push($html, 'var ads='.json_encode($ads).';');
array_push($html, '$(document).ready(function(){ adloader.load(ads, '.self::$_step.', '.intval(self::$_async).'); });');
array_push($html, '</script>');
}
return implode("\r\n", $html);
}
/** 判断是否需要强制同步加载的浏览器 */
private static function checkbrowser(){
$user_agent = $_server['http_user_agent'];
if(strstr($user_agent,'msie')!=''){
return false;
}
return true;
}
} // class end
?>
adconfig.php文件如下:
<?php
/** 广告配置文件 **/
return array(
'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
*/
var adloader = (function(){
var _ads = [], // 广告集合
_step = 300, // 广告加载间隔
_async = true, // 是否异步加载
_loaded = 0; // 已经加载的广告数
/** loadad 循环加载广告
* @param int c 第几个广告
*/
function loadad(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{ // 将同步加载的广告显示
var ad_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();
}
}
/** 加载完广告后处理 */
function completead(){
_loaded ++;
settimeout(function(){
loadad(_loaded);
}, _step);
}
/** 获取广告
* @param array ad 广告参数
*/
function getscript(ad){
var ret = null;
switch(ad.type){
case 'openx': // openx code ad
ret = 'data:text/javascript;base64,' + ad.zoneid + 'dmfyig0zx3ugpsaobg9jyxrpb24uchjvdg9jb2w9psdodhrwczonpydodhrwczovl2fkcy5ubwcuy29tlmhrl3d3dy9kzwxpdmvyes9hanmucghwjzonahr0cdovl2fkcy5ubwcuy29tlmhrl3d3dy9kzwxpdmvyes9hanmucghwjyk7cnzhcibtm19yid0gtwf0ac5mbg9vcihnyxrolnjhbmrvbsgpkjk5otk5otk5otk5ktskawygkcfkb2n1bwvudc5nqvhfdxnlzckgzg9jdw1lbnqutufyx3vzzwqgpsanlcc7cmrvy3vtzw50lndyaxrlicgiphnjciirimlwdcb0exblpsd0zxh0l2phdmfzy3jpchqnihnyyz0niittm191ktskzg9jdw1lbnqud3jpdgugkci/em9uzwlkpsigkyb6b25lawqpowpkb2n1bwvudc53cml0zsaojyzhbxa7y2i9jyarig0zx3ipowppziaozg9jdw1lbnqutufyx3vzzwqgit0gjywnksbkb2n1bwvudc53cml0zsaoiizhbxa7zxhjbhvkzt0iicsgzg9jdw1lbnqutufyx3vzzwqpowpkb2n1bwvudc53cml0zsaozg9jdw1lbnquy2hhcnnldca/iccmyw1wo2noyxjzzxq9jytkb2n1bwvudc5jagfyc2v0idogkgrvy3vtzw50lmnoyxjhy3rlclnldca/iccmyw1wo2noyxjzzxq9jytkb2n1bwvudc5jagfyywn0zxjtzxqgoianjykpowpkb2n1bwvudc53cml0zsaoiizhbxa7bg9jpsigkyblc2nhcguod2luzg93lmxvy2f0aw9uksk7cmlmichkb2n1bwvudc5yzwzlcnjlcikgzg9jdw1lbnqud3jpdgugkcimyw1wo3jlzmvyzxi9iiarigvzy2fwzshkb2n1bwvudc5yzwzlcnjlcikpowppziaozg9jdw1lbnquy29udgv4dckgzg9jdw1lbnqud3jpdgugkcimy29udgv4dd0iicsgzxnjyxblkgrvy3vtzw50lmnvbnrlehqpktskawygkgrvy3vtzw50lm1tbv9mbykgzg9jdw1lbnqud3jpdgugkcimyw1wo21tbv9mbz0xiik7cmrvy3vtzw50lndyaxrlicgijz48xc9zy3iikyjpchq+iik7';
break;
case 'url': // url ad
ret = ad.url;
break;
}
return ret;
}
/** 同步加载广告
* @param array ad 广告参数
*/
function writead(ad){
switch(ad.type){
case 'openx':
var m3_u = (location.protocol=='https:'?'https://ads.nmg.com.hk/www/delivery/ajs.php':'http://ads.nmg.com.hk/www/delivery/ajs.php');
var m3_r = math.floor(math.random()*99999999999);
if (!document.max_used) document.max_used = ',';
document.write ("<scr"+"ipt type='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 ('<script type="text/javascript" src="' + ad.url + '"></script>');
break;
}
}
obj = {
/** 加载广告
* @param array ads 广告集合
* @param int step 广告加载间隔
* @param boolean async true:异步加载 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);
}
}
}
return obj;
}());
/* craploader */
var craploader = (function() {
var ishijacked = 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")
};
function checkqueue () {
if(queue.length) {
loadscript( queue.shift() );
} else if(loading === 0 && globaloptions.autorelease) {
debug("queue is empty. auto-releasing.");
publ.release();
}
}
function checkwritebuffer (obj) {
var buffer = writebuffer[obj.domid],
returnedel;
if(buffer && buffer.length) {
writehtml( buffer.shift(), obj );
} else {
while (returnedelements.length > 0) {
returnedel = returnedelements.pop();
var id = returnedel.id;
var elindoc = getelementbyid(id);
if (!elindoc) { continue; }
var parent = elindoc.parentnode;
elindoc.id = id + "__tmp";
parent.insertbefore(returnedel, elindoc);
parent.removechild(elindoc);
}
finished(obj);
}
}
function debug (message, obj) {
if(!globaloptions.debug || !window.console) { return; }
var objextra = "";
if(obj) {
objextra = "#"+obj.domid+" ";
var depth = obj.depth;
while(depth--) { objextra += " "; }
}
console.log("craploader " + objextra + message);
}
function extend (t, s) {
var k;
if(!s) { return t; }
for(k in s) {
t[k] = s[k];
}
return t;
}
function finished (obj) {
if(obj.success && typeof obj.success === "function") {
obj.success.call( document.getelementbyid(obj.domid) );
}
checkqueue();
}
function flush (obj) {
var domid = 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);
}
function getcachedelbyid (domid) {
return elementcache[domid] || (elementcache[domid] = document.getelementbyid(domid));
}
function getelementbyid (domid) {
return ( publ.orggetelementbyid.call ?
publ.orggetelementbyid.call(document, domid) :
publ.orggetelementbyid(domid) );
}
function getelementbyidreplacement (domid) {
var el = getelementbyid(domid),
html, frag, div, found;
function traverseforelbyid(domid, el) {
var children = 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) { return child; }
if(child.children && child.children.length) {
var tmp = traverseforelbyid(domid, child);
if (tmp) return tmp;
}
}
}
}
function searchforalreadyreturnedel(domid) {
var i, l, returnedel;
for(i=0,l=returnedelements.length; i<l; i++) {
returnedel = returnedelements[i];
if(returnedel.id === domid) { return returnedel; }
}
}
if(el) { return el; }
if (returnedelements.length) {
found = searchforalreadyreturnedel(domid);
if (found) {
return found;
}
}
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);
}
return found;
}
}
var globaleval = (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);
});
}());
function isscript (html) {
return html.tolowercase().indexof("<script") === 0;
}
function runfunc (obj) {
obj.func();
obj.depth++;
flush(obj);
}
function loadscript (obj) {
loading++;
// async loading code from jquery
var script = 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);
var done = false;
// attach handlers for all browsers
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++;
// use insertbefore instead of appendchild to circumvent an ie6 bug.
// this arises when a base node is used (#2709 and #4378).
head.insertbefore( script, head.firstchild );
settimeout(function() {
if(!script.loaded) { throw new error("script not loaded: " + script.src); }
}, obj.timeout);
}
function logscript (obj, code, lang) {
debug((code ?
"inline " + lang + ": " + code.replace("\n", " ").substr(0, 30) + "..." :
"inject " + obj.src), obj);
}
function separatescriptsfromhtml (htmlstr) {
return split(htmlstr, splitscriptsregex);
}
function split (str, regexp) {
var match, previndex=0, tmp, result = [], i, l;
if(support.splitwithcapturingparentheses) {
tmp = str.split(regexp);
} else {
// cross browser split technique from steven levithan
// 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]); }
}
return result;
}
function stripnoscript (html) {
return html.replace(/<noscript>[\s\s]*?<\/noscript>/ig, "");
}
function trim (str) {
if(!str) { return str; }
return str.replace(/^\s*|\s*$/gi, "");
}
function writehtml (html, obj) {
if( isscript(html) ) {
var dummy = document.createelement("div");
dummy.innerhtml = "dummy<div>" + html + "</div>"; // trick for ie
var script = dummy.children[0].children[0];
var lang = 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 {
var code = trim( script.text );
if(code) {
logscript( obj, code, lang);
globaleval( code, lang);
}
flush(obj);
}
} else {
var container = getcachedelbyid(obj.domid);
if(!container) {
throw new error("craploader: unable to inject html. element with id '" + obj.domid + "' does not exist");
}
html = trim(html); // newline before <object> cause weird effects in ie
if(html) {
container.innerhtml += html;
}
checkwritebuffer(obj);
}
}
function writereplacement (str) {
inputbuffer.push(str);
debug("write: " + str);
}
function openreplacement () {
// document.open() just returns the document when called from a blocking script:
// http://www.whatwg.org/specs/web-apps/current-work/#dom-document-open
return document;
}
function closereplacement () {
// document.close() does nothing when called from a blocking script:
// 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("browsers onload is not reliable. disabling parallel loading.");
}
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("not in hijacked mode. auto-hijacking.");
this.hijack();
}
var defaultoptscopy = extend({}, defaultoptions);
var obj = extend(defaultoptscopy, options);
obj.depth = 0;
if (!obj.domid) {
obj.domid = "craploader_" + new date().gettime();
var span = 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 (typeof domid !== "string") {
options = domid;
domid = undefined;
}
this.handle(extend({
src: src,
domid: domid
}, options));
},
runfunc: function(func, domid, options) {
if (typeof domid !== "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);
}
};
return publ;
}());
demo.php示例程序如下:
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title> ad loader </title>
<style type="text/css">
.banner1{margin:10px; border:1px solid #cccccc; width:728px; height:90px;}
.banner2{margin:10px; border:1px solid #cccccc; width:300px; height:250px;}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<div class="banner1" id="ad_728x90"></div>
<div class="banner2" id="ad_300x250"></div>
<div class="banner2" id="ad_l2_300x250"></div>
<?php
function showad($channel='', $step='', $async=''){
include('adloader.class.php');
$ad_config = include('adconfig.php');
adloader::setconfig($ad_config, 'adloader.js');
return adloader::load($channel, $step, $async);
}
echo showad('case_openx'); // 异步加载
//echo showad('case_url'); // url方式异步加载
//echo showad('case_sync_openx', 300, false); // 同步加载
?>
</body>
</html>
adurl.php文件如下:
<?php
$zoneid = isset($_get['zoneid'])? intval($_get['zoneid']) : 0;
if($zoneid){
?>
var zoneid = <?=$zoneid ?>;
var m3_u = (location.protocol=='https:'?'https://ads.nmg.com.hk/www/delivery/ajs.php':'http://ads.nmg.com.hk/www/delivery/ajs.php');
var m3_r = math.floor(math.random()*99999999999);
if (!document.max_used) document.max_used = ',';
document.write ("<scr"+"ipt type='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程序设计有所帮助。
评论列表:
发布于 3天前回复该评论
发布于 3天前回复该评论
发布于 3天前回复该评论
发布于 2天前回复该评论
发布于 2天前回复该评论
发布于 2天前回复该评论
发布于 2天前回复该评论
发布于 1天前回复该评论