1. 動态加載JS檔案
第一種方法:
test.php
複制代碼 代碼示例:
test6.php
複制代碼 代碼示例:
header('Content-Type: application/x-javascript; charset=UTF-8');
$str = $_GET["str"];
?>
// javascript document
// by www.jbxue.com
alert('<?php echo $str; ?>');
function tester(string)
{
string ? alert(string) : alert('you call a function named tester');
}
?>
第二種方法:
test.php
複制代碼 代碼示例:
function loadjs(url,callback){
var head = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.onload = script.onreadystatechange = script.onerror = function (){
if (script && script.readyState && /^(?!(?:loaded|complete)$)/.test(script.readyState)) return;
script.onload = script.onreadystatechange = script.onerror = null;
script.src = '';
script.parentNode.removeChild(script);
script = null;
callback();
}
script.charset = "gb2312";
script.src = url;
try {
head.appendChild(script);
} catch (exp) {}
}
function loadmultijs(url,callback){
if(Object.prototype.toString.call(url)==='[object Array]'){ //是否數組
this.suc = 0; //加載計數
this.len = url.length; //數組長度
var a = this;
for(var i = 0;i < url.length;i++){
loadjs(url[i],function(){ a.suc++; if(a.suc == a.len) try{callback();}catch(e){} });
}
}
else if(typeof(url) == 'string') loadjs(url,callback);
}
loadjs("test5.php?return=value",function(){ alert(value); tester(value); });
test5.php
複制代碼 代碼示例:
var value="this is value.";
加載多JavaScript檔案的執行個體:
複制代碼 代碼示例:
var url = [
'ajax.php?ajax=1',
'functions.js'
];
loadmultijs(url,function(){ alert("加載完畢。"); });
2. 動态加載css檔案
test.php
複制代碼 代碼示例:
this document has a #e4e4e4 background, a 300px/400px div, and a arial/24px/red words.
div.php
複制代碼 代碼示例:
// declare the output of the file as CSS
header('Content-type: text/css');
// include the script
//include('others.php');
$width = $_GET['w'];
$height = $_GET['h'];
?>
複制代碼 代碼示例:
div{width:=$width?>px;height:=$height?>px;border:blue 1px solid;}
fonts.php
複制代碼 代碼示例:
// declare the output of the file as CSS
header('Content-type: text/css');
// include the script
//include('others.php');
$size = $_GET['s'];
$color = $_GET['c'];
?>
body{font-family:arial;font-size:=$size?>px;color:=$color?>}
就是這些了,php動态加載js與css的方法就介紹完了,建議大家親自動手測試下,看看具體的實作有沒有問題。