当库在页脚中加载时,基于PHP条件调用Javascript


Calling Javascript based on PHP conditional when libraries load in the footer

我在php页面的主体中有以下内容:

<?php if($foo) : ?>
    <script>
        js_func();
    </script>
<?php else: ?>
    //Do Something else
<?php endif; ?>

基于PHP条件,我要么想运行js_func(),要么不想运行。

但是,如果我在页面底部加载所有脚本(包括定义js_func()的脚本),这将导致错误。

一种可能的解决方案是在调用js_func()之前加载外部脚本,但我知道出于性能原因,我不应该这样做。

我可以使用$(document).ready(function(){});但这只是移动了错误,因为jQuery也加载在页脚中。

我唯一能想到的其他选择是使用window.onload或从不内联调用js函数。其他人是如何解决这个问题的?

非常感谢。

编辑:

@尼罗——我不知道你是什么意思。为什么我要注释掉要执行的代码?@haynar1658-我不想在其他场景中执行JS。@马修·布兰卡特-明白。这就引出了我的问题,在实例化函数之前,确保我需要的js加载的最佳方法是什么?在它之前包括脚本?使用window.onload?等等

我认为你在为自己的背部制造一根棍子。根据您描述的问题,您希望将所有函数定义脚本块放在调用它们的位置之后。这是不可能的
如果您确实需要这样做,这会有帮助吗?:

<script>    
    var fns = []; /* use fns to keep all the js code  
                     which call the functions defined after. */  
</script>

<script>
    //wrapp your code in a function and then push it into fns.   
    fns.push(function(){  
        js_func();  
    }) 
</script>

//script tags for loading your function  definition js script.  
<script src="path/to/jquery-any-version.js"></script>  
<script src="path/to/other-libraries.js"></script>

<script>
    //after your definition js scripts are loaded ,  call all functions in fns  
    for(var i=0, len=fns.length; i<len; i++){  
        var fn = fns[i];  
        fn.apply(this, []/* arguments that provided  as an array */);  
    }
</script>

只需将脚本移到顶部即可。

差别(如果有的话)很小
并不是所有开发人员都"接受"将<script>s放在<head>中会减慢页面速度的说法。

您是否尝试在PHP中回显它?

<?php if($foo) {
echo "<script> js_func(); </script>";
}else{
echo "something else";
}