Kelvin
Kelvin

Reputation: 585

Dynamically load Javascript

Do any one have similar experience? I would like to load an external javascript dynamically while I click on a specific page. Below is the code I wrote:

    $("#tab-4-content").load("/reg.php?id="+this.id+"&ads="+$(this).data('ads')+"&f="+$(this).data('file')+"&mid="+$(this).data('mid'));
$.ajax({
  url: "http://www.mydomain/validation.js",
  dataType: "script",
  cache: false,
    }).done(function() {
        console.log("success load livevalidation");
    });
    $.mobile.changePage("#tab-4");
}); // tab-4-content click

validation.js is the script to valid the form input. When the cache setting is true, then the script seems not to be loaded successfully because an error prompted in Chrome Javascript Console. After I change it to false, it works.

The problem is if I keep the browser on without clicking the #tab-4-content for a day, I tried the click it after the day, the error prompted again, then I have to change the cache to true, execute one and then false again, it resume normal. I have no idea how the cache do, is there time expire issue and the error is caused by the cache setting?

Error prompted: Uncaught ReferenceError: Validation is not defined

Best regards,

Kelvin

Upvotes: 0

Views: 121

Answers (2)

Jason
Jason

Reputation: 892

Bypass all the extra coding. Just create a script tag and source to the javascript file you need in the page you are loading.

<script src="/validation.js"></script>

Upvotes: 0

morgan9999
morgan9999

Reputation: 801

this is .getScript function, you can try this

$.getScript( "http://www.mydomain/validation.js" )
.fail(function() {
    // so something
}).done(function() {
    console.log("success load livevalidation");
});

but i do think the error is on validation.js itself like Sukima said, check on that file first if this doesn't work.

Upvotes: 2

Related Questions