Skip to Main Content
High Performance Web Sites
book

High Performance Web Sites

by Steve Souders
September 2007
Intermediate to advanced content levelIntermediate to advanced
170 pages
4h 24m
English
O'Reilly Media, Inc.
Content preview from High Performance Web Sites

Avoiding Duplicate Scripts

One way to avoid accidentally including the same script twice is to implement a script management module in your templating system. The typical way to include a script is to use the SCRIPT tag in your HTML page:

<script type="text/javascript" src="menu_1.0.17.js"></script>

An alternative in PHP would be to create a function called insertScript:

<?php insertScript("menu.js") ?>

While we're tackling the duplicate script issue, we'll add functionality to handle dependencies and versioning of scripts. A simple implementation of insertScript follows:

<?php
function insertScript($jsfile) {
    if ( alreadyInserted($jsfile) ) {
        return;
    }
    pushInserted($jsfile);

    if ( hasDependencies($jsfile) ) {
        $dependencies = getDependencies($jsfile);
        Foreach ($dependencies as $script) {
            insertScript($script);
        }
    }
    echo '<script type="text/javascript" src="' . getVersion($jsfile) . '"></script>";
}
?>

The first time a script is inserted, we'll reach pushInserted. This adds the script to the alreadyInserted list for the page. If that script is accidentally inserted again, the test for alreadyInserted will not add the script again, thus solving the duplicate script issue.

If this script has dependencies, those prerequisite scripts are inserted. In this example, menu.js might depend on events.js and utils.js. You can capture these dependency relationships using a hash or database. For simpler sites, dependencies can be maintained manually. For more complex sites, you may choose to automate ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Even Faster Web Sites

Even Faster Web Sites

Steve Souders
Back-end Performance

Back-end Performance

Bruno Skvorc, Christopher Pitt, Tonino Jankov, Reza Lavaryan, Daniel Berman

Publisher Resources

ISBN: 9780596529307Errata Page