In this example upon a button click we load a JavaScript function and then execute it.
<html> <head> <title>jQuery load JavaScript library on demand</title> <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js" type="text/javascript"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $('#myButton').click(function() { $.getScript('app.js',function(){ addSomeText(); }); }); }); </script> </head> <body> <div id="myExample"> <form id="myForm" action=""> <fieldset> <legend> Dynamically load JavaScript library before calling a function </legend> <input id="myButton" type="button" value="This button will load a function dynamically before executing"/> </fieldset> <fieldset> <legend>See Result in this Section:</legend> <div id="myResults"></div> </fieldset> </form> </div> </body> </html>
JavaScript file that's loaded dynamically - app.js
function addSomeText() { $("#myResults") .html("<b>Well I just loaded the JavaScript file app.js</b>" + " and then put some HTML content on this page!"); }
Please note: When loading JavaScripts dynamically with jQuery’s getScript it adds a cache busting parameter to the request URL causing the script to be loaded fresh each time. See screen below
No comments:
Post a Comment
NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.