How to load script with jquery.load()?

When you say “the script doesn’t work” do you mean there’s javascript in the page you’re loading through ajax?

It’s not going to work, ever, at least not directly.

You have two choices. Parse out the script from the content you’ve loaded, and use eval to run it.

A better way is to use $.getScript to load (and execute) javascript. If you want to bind your javascript with the HTML you’ve loaded, then you need some convention to identify the script. For example you could include a tag in your dynamically loaded html:

<span style="display:none;" id="script">/scripts/somescript.js</span>

Then look for a span with id=”script” when you load the content, if you find it, use $.getScript to load the script it identifies.

example…

$.load('content.html #toLoad', function(data){
    var $script = $(data).find('span[id=script]');
    if ($script.length) {
        $.getScript($script.html());
        // remove the span tag -- no need to render it
        $script.remove();
    }
    $('#content').html(data);
});

Leave a Comment