Dynamically include javascript files only once

I have a javascript function that I write that is used to include an external JS file, but only once. The reason I need such a function is because it is called when some content is loaded via AJAX, and I need to run the page-specific code for that content (no, just use .livewon't cover it).

Here is my attempt, shortened for brevity:

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

This works fine: the function is called, it loads the external file, and this file is launched at boot. Perfect.

The problem is that it will always reload this external file: the query that I use to check for the existence of the script always finds nothing!

When debugging, I added a few lines:

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

( HTML Firebug) script .

, , , , ( ) , JS .

- , ?

+5
3

jQuery ; , . append($node) jQuery :

jQuery.ajax({
  url: $node.src,
  async: false,
  dataType: "script"
})

Woops! (, ) jQuery XMLHttpRequest .js "eval" <script> (!) .js. eval, .

, XMLHttpRequest - , jQuery <script> <head>.

jQuery, , :

head.removeChild(script);

.length! .

, jQuery .

document.getElementsByTagName('head')[0]
  .appendChild(
    document.createElement('script')
  )
  .src = filename;

, , .

+5

, . LazyLoad, . jQuery.

+3

script -tag "text" script. (, , IE6, ...).

( , - , , , ? ...!):

var script_source_code_string = <some dynamically loaded script source code>;
var $n = $("<script></script>");
$n.get(0).text = script_source_code_string;
$(document.body).append($n);

( jquery, jquery, ):

var script_source_code_string = <some dynamically loaded script source code>;
var s = document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(s);
s.text = script_source_code_string;
0
source

All Articles