Load a JavaScript file dynamically

Load a JavaScript file dynamically using jQuery

jQuery.getScript()
Load a JavaScript file from the server using a GET HTTP request, then execute it.

Eg:
$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
  console.log( data ); // Data returned
  console.log( textStatus ); // Success
  console.log( jqxhr.status ); // 200
  console.log( "Load was performed." );
});
By default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested. You can override this feature by setting the cache property globally using $.ajaxSetup():

$.ajaxSetup({
  cache: true
});
Sample code and demo

Demo

No comments:

Post a Comment