2

我正在尝试为 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()等到所有脚本都排队后才能运行?或者....有没有更好的方法来允许脚本队列,以便我可以在最后将所有脚本写入文档?

4

3 回答 3

0

如果都运行在同一个文件中,能否将body内容设为变量$body,先加载,再回显到<body>section中?

于 2012-04-12T21:39:23.253 回答
0
change
<html>
<head>
<?php write_scripts_header();?>
</head>
<body>
<?php write_scripts_footer();?>
</body>
</html>

print "<html><head>".write_scripts_header()."</head><body>".write_scripts_footer()."</body></html>";
于 2012-04-12T21:41:18.033 回答
0

尝试使用模板引擎,例如Twig,您将能够在准备好脚本数组后输出 html。

于 2012-04-12T21:42:31.060 回答