我正在尝试为 javascript 文件创建队列函数。基本上,这就是我希望它工作的方式:我想创建一个函数,它将接收所有发送给它的 javascript,并将它们放在页面上的适当位置(即页眉或页脚,以及依赖脚本之上)。
我想说:这是一个脚本。按照它应该在的顺序将它添加到队列中。然后,在所有脚本都排队后,运行函数将它们写入页面。到目前为止,我的代码如下所示:
$scripts = array();
function enqueue_script($src="", $script_name="", $script_data="",
$script_dependencies=array(), $force_header=false, $additional_atts=array()){
global $scripts;
//run check for duplicates
//run check for dependencies already in the variable
//run checks to see if this script depends on other scripts
//$scripts array is saved in increments of 10 to allow for up to
//9 dependants
$i = count($scripts);
$i = ($i*10)+10;
$scripts[$i]['src'] = $src;
$scripts[$i]['script_name'] = $script_name;
$scripts[$i]['script_data'] = $script_data;
$scripts[$i]['dependencies'] = $script_dependencies;
$scripts[$i]['force_header'] = $force_header;
$scripts[$i]['atts'] = $additional_atts;
}
function write_scripts_header() {
global $scripts;
$echo = "";
$atts = "";
//create script tag for insertion in header
foreach($scripts as $s){
if($s['force_header']){
foreach($s['atts'] as $a => $v){
$atts .= " {$a}='{$v}'";
}
if($s['src']!=""){
$echo .= "<script src='{$s['src']}'{$atts}></script>\n";
} else {
$echo .= "<script{$atts}>{$s['script_data']}</script>\n";
}
}
}
echo $echo;
}
function write_scripts_footer() {
global $scripts;
$echo = "";
$atts = "";
//create script tag for insertion in footer
foreach($scripts as $s){
if(!$s['force_header']){
foreach($s['atts'] as $a => $v){
$atts .= " {$a}='{$v}'";
}
if($s['src']!=""){
$echo .= "<script src='{$s['src']}'{$atts}></script>\n";
} else {
$echo .= "<script{$atts}>{$s['script_data']}</script>\n";
}
}
}
echo $echo;
}
然后,在 HTML 文件部分:
<html>
<head>
<?php write_scripts_header();?>
</head>
<body>
<?php write_scripts_footer();?>
</body>
</html>
如果最后加载 HTML 部分,这可以正常工作。但是,如果我在正文标记的中间有一个包含,并且该包含需要enqueue_script()
在标题中,那么当函数运行$scripts
时变量还没有准备好。write_scripts_header()
如何制作write_scripts_header()
并write_scripts_footer()
等到所有脚本都排队后才能运行?或者....有没有更好的方法来允许脚本队列,以便我可以在最后将所有脚本写入文档?