Peter Stuart
Peter Stuart

Reputation: 2434

Using .load(url) doesn't let me use additional javascript

I have this code in index.html file:

$(function(){
    $('a#link').live('click', function(e){ 
        $("div#element").load("file.html");
    });
});

In the file.html I have this code at the top

<script src="file.js" type="javascript"></script>

When I click on the link, the file loads fine, however the (according to firebug) the JavaScript file doesn't load. Does anyone know why? I tried put the script tags in the index.html file aswell, but it doesn't work like that.

Upvotes: 0

Views: 411

Answers (4)

Pierre
Pierre

Reputation: 19071

Try loading the page scripts after the page is loaded in your div as follow:

$(function(){
    $('a#link').live('click', function(e){ 
        $("div#element").load("file.html", function(){
            $.getScript("file.js", function(){
               // second page's scripts are loaded...
            });
        });
    });
});

A simpler way to fix this, as Pointy stated, is either to fix the type attribute or omit it.

Upvotes: 3

ncank
ncank

Reputation: 956

if you need to load scripts, you can use getScript method instead

Upvotes: 2

Pointy
Pointy

Reputation: 413717

The problem is that when you ".load()" scripts like that, jQuery will only run them if there's no "type" attribute, or if the "type" attribute has the precise value "text/javascript". Anything else and it's completely ignored.

Your script has just "javascript" for that attribute, so it's thrown out.

Upvotes: 0

Dominic Green
Dominic Green

Reputation: 10258

When loading in html with javascript you normally need to remove the html head and body tags to make the javascript fire. I think this is also mentioned here jQuery .load() call doesn't execute javascript in loaded html file

Upvotes: 0

Related Questions