Sometimes we have some requirement to include the required JavaScript files programmatically.
Is it possible to includes file at runtime?
Yes, it is possible. Lets take an example where we need to includes the files programmatically.
Ex: I am a web widgets developer. I am developing some widgets using html, Javascript and CSS, and will give few lines of script to client(who will use the application, I mean who will use the widgets in their site.). Why should I give them the virtual path for all my script files. It is better if I programtically include the required files..
How should I achieve this ?
Lets me explain the answer by one example.
We need one JavaScript file named require-jquery.js, you can download this file from here
I have one page lunch.htm, here I want to include the few JavaScript files
jQuery+RequireJS Sample Page
Load the required javascripts files dynamically
Download files
I have one lunchChat.js file, where I am providing the name of the required js files, to include in the above mentioned page.
IncludeRequired.js require(["jquery", "req_first", "req_second", "req_third", "req_fourth", "req_fifth"], function($) { $(function() { $('body').Mritunjay().Niraj().Srikant().Subodh().Sumit(); }); }); define("main", function(){});
Here we can provide the virtual path of the files. In this example all files are in same label and the required files are given below.
req_first.js $.fn.Sumit = function() { return this.append('
Please download req_first !!!'); }; req_second.js $.fn.Subodh = function() { return this.append('
Please download req_second !!!'); }; req_third.js $.fn.Srikant = function() { return this.append('
Please download req_third !!!'); }; req_fourth.js $.fn.Niraj = function() { return this.append('
Please download req_fourth !!!'); }; req_fifth.js $.fn.Mritunjay = function() { return this.append('
Please download req_fifth !!!'); };
Lets have a look at the result.