【问题标题】:PHP add external css and js file in layout templatePHP在布局模板中添加外部css和js文件
【发布时间】:2017-02-28 16:31:22
【问题描述】:

请建议我如何在 php 布局模板中添加外部 css/js 文件。 我当前的代码附在下面。

Class Template{
  public function header() //it loads header.php file
  public function footer(){
     $footer = file_get_contents('footer.php');
      //this function load js file
      $search[] = "%__script__%";
      if(isset($this->script) && file_exists($this->script)){
        $replace = "<script src=\"$this->ready_script\">";
      }
      return str_replace($search, $replace, $header);
  }
}

这是footer.php文件

</body>
</html>
%__script__%

这个函数可以很好地调用每个页面中的页眉和页脚函数。 但我想像这样维护单个布局文件

我的布局文件

$temp = new Template();
echo $temp->header();
__CONTENT GOES HERE WHICH IS LOADED FROM AJAX__
echo $temp->footer();

我想在布局文件 html 输出的末尾添加外部 js 文件

*** Update ***

脚本是使用内容页面(内容页面)中的对象定义的,例如 $temp->script_src = "js file name" 。如果 script_src 找到,那么它将加载到 html 文件末尾的布局文件(layout.php)中

** My file structure **
App
  -- header
  -- content (in content external js file url defined by $temp->script property
  -- footer
  -- if $temp->script property found then load js using <script> tag

【问题讨论】:

    标签: javascript php templates


    【解决方案1】:

    您的问题对我来说有点不清楚,但是如果您想添加一个外部 js 文件,请在您的 html 输出末尾添加,请尝试以下操作:

    document.addEventListener("DOMContentLoaded", function() {
        var bodyLoaded = document.body,
            url = "http://yourexternal.com/script.js",
            script = document.createElement('script');
        script.type = "text/javascript";
        script.src = url;    
        bodyLoaded.appendChild(script);
    });  
    

    【讨论】:

    • 感谢您的回复。脚本是使用内容页面(内容页面)中的对象定义的,例如 $temp->script_src = "js file name" 。如果 script_src 找到,那么它将加载到 html 文件末尾的布局文件(layout.php)中。
    猜你喜欢
    • 1970-01-01
    • 2014-12-14
    • 2020-10-18
    • 1970-01-01
    • 2017-08-30
    • 2010-12-04
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    相关资源
    最近更新 更多