tags:

views:

37

answers:

2

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.

+2  A: 

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.

Ignacio Vazquez-Abrams
by most browsers, do you know which are exceptions?
Mild Fuzz
I think there was one back in... 1998 or so that didn't do it.
Ignacio Vazquez-Abrams
that's wrong, a browser will only load a resource once if you tell it to only load it once.
Petah
@Petah: Try loading a page with 100 `img` elements all with the same source on a very slow link.
Ignacio Vazquez-Abrams
@Ignacio, My point exactly, you told the browser to load 100 `img` elements instead of using 1 CSS image background. Also if you send the right cache headers the browser wont request for the image again until the cache expires.
Petah
+2  A: 

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>
Petah