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

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 this form, and it might be loaded several times into a page. It strikes me as the best way to handle things if the form itself loads the script, so it doesn't load if not needed, but this leads me to need to check if the script is already loaded to avoid reloading and adding to page load times and bandwidth use.

Answers:

Answer

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.

Answer

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>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.