Dynamically including javascript files only once
<p>I have a javascript function I'm writing which is being used to include an external JS file, but only once. The reason I need such a function is because it is being called when some content is loaded via AJAX and I need to run page-specific code to that content (no, just using <code>.live</code> won't cover it).</p>

<p>Here's my attempt, shortened for brevity:</p>

<pre><code>$.include_once = function(filename) {
    if ($("script[src='" + filename + "']").length === 0) {
        var $node = $("&lt;script&gt;&lt;/script&gt;")
            .attr({
                src : filename,
                type : "text/javascript"
            })
        ;
        $(document.body).append($node);
    }
};
</code></pre>

<p>This works fine: the function is called, it loads the external file, and that file is being run when loaded. Perfect.</p>

<p>The problem is that it will always re-load that external file: the query I'm using to check for the presence of the script always finds nothing!</p>

<p>When debugging this, I added some lines:</p>

<pre><code>alert($("script").length);     // alerts: 4
$(document.body).append($node);
alert($("script").length);     // alerts: 4
</code></pre>

<p>Looking in the dynamic source (the HTML tab of Firebug), I can't find the script tag at all.</p>

<p>I know that I could maintain an array of files that I've previously included, but I was hoping to go with a method such as this, which (if it worked), seems a bit more robust, since not all the JS files are being included in this way.</p>

<p><strong>Can anyone explain the behaviour seen in this second snippet?</strong></p>
