By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,364 Members | 1,268 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,364 IT Pros & Developers. It's quick & easy.

On Demand Loading Js Files?

P: 17
I developed project using requirejs architecture where all dependancies and js metioned in app.js files and in repective modules files under define tag metioned required jquery modules.
In this i used some third party lib like kendo and all and some i created. So when i run my application under network tab i able to see it will download all js files which i metioned in define function but right now they are not required until i click some thing. So how i can achieve on demand loading and minimize the request.
Apr 2 '20 #1
Share this Question
Share on Google+
2 Replies

P: 37
You may write dynamic script tags (using Prototype):

new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"});
The problem here is that we do not know when the external script file is fully loaded.

We often want our dependant code on the very next line and like to write something like:

if (iNeedSomeMore) {
Script.load("myBigCodeLibrary.js"); // includes code for myFancyMethod();
myFancyMethod(); // cool, no need for callbacks!
There is a smart way to inject script dependencies without the need of callbacks. You simply have to pull the script via a synchronous AJAX request and eval the script on global level.

If you use Prototype the Script.load method looks like this:

var Script = {
_loadedScripts: [],
include: function(script) {
// include script only once
if (this._loadedScripts.include(script)) {
return false;
// request file synchronous
var code = new Ajax.Request(script, {
asynchronous: false,
method: "GET",
evalJS: false,
evalJSON: false
// eval code on global level
if (Prototype.Browser.IE) {
} else if (Prototype.Browser.WebKit) {
new Element("script", {
type: "text/javascript"
}), {
text: code
} else {
// remember included script
Apr 3 '20 #2

P: 17
By doing this code becomes more cluttered so is there any clean way to do this.
3 Weeks Ago #3

Post your reply

Sign in to post your reply or Sign up for a free account.