天天看点

php加载程序文件的方式_php 动态加载JavaScript或css文件的方法

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的方法就介绍完了,建议大家亲自动手测试下,看看具体的实现有没有问题。