using php to check is a javascript file has been loaded?

前端 未结 2 690
悲&欢浪女
悲&欢浪女 2021-01-21 15:20

Can I use a script to check if a JS file is loaded?

I have a function, which places a form on a page with javascript controls. I don\'t know where the user will use th

相关标签:
2条回答
  • 2021-01-21 16:04

    No. The page isn't seen until the PHP script has flushed all its output, by which time it's too late to do anything. But most browsers are smart enough to only load an external resource once per page anyway.

    0 讨论(0)
  • 2021-01-21 16:11

    You should have an asset management system in your PHP to see whats being included into the page.

    Ultra simple example (derived from link):

    <?php
    class Page {
        private static $head = array();
        private static $js_assets = array();
        private static $content = '';
        static function add_head($tag) {
            self::$head[] = $tag;
        }
        static function render_head() {
            foreach (self::$head as $tag) echo $tag;
            foreach (self::$js_assets as $js) echo '<script src="'.$js.'" type="text/javascript"></script>';
        }
        static function render_content() {
            echo self::$content;
        }
        static function read_content($file) {
            ob_start();
            require $file;
            self::$content = ob_get_clean();
        }
        static function render_layout($file) {
            require $file;
        }
        static function add_js($js) {
            if (!in_array($js, self::$js_assets)) {
                self::$js_assets[] = $js;
            }
        }
    }
    
    Page::add_js('/javascripts/application.js');
    Page::read_content('view.php');
    Page::render_layout('layout.php');
    ?>
    

    layout.php:

    <html>
        <head><?php Page::render_head(); ?></head>
        <body>
            <div id="header"></div>
    
            <div id="content"><?php Page::render_content(); ?></div>
    
            <div id="footer"></div>
        </body>
    </html>
    

    view.php:

    <?php Page::add_head('<title>Hello World!</title>'); ?>
    <h1>Hello</h1>
    <p>World</p>
    
    0 讨论(0)
提交回复
热议问题