On Demand Loading Js Files?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • SagarJaybhay
    New Member
    • Feb 2019
    • 17

    On Demand Loading Js Files?

    Hello,
    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.
  • lewish95
    New Member
    • Mar 2020
    • 33

    #2
    You may write dynamic script tags (using Prototype):

    new Element("script ", {src: "myBigCodeLibra ry.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("my BigCodeLibrary. 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._loadedSc ripts.include(s cript)) {
    return false;
    }
    // request file synchronous
    var code = new Ajax.Request(sc ript, {
    asynchronous: false,
    method: "GET",
    evalJS: false,
    evalJSON: false
    }).transport.re sponseText;
    // eval code on global level
    if (Prototype.Brow ser.IE) {
    window.execScri pt(code);
    } else if (Prototype.Brow ser.WebKit) {
    $$("head").firs t().insert(Obje ct.extend(
    new Element("script ", {
    type: "text/javascript"
    }), {
    text: code
    }
    ));
    } else {
    window.eval(cod e);
    }
    // remember included script
    this._loadedScr ipts.push(scrip t);
    }
    };

    Comment

    • SagarJaybhay
      New Member
      • Feb 2019
      • 17

      #3
      By doing this code becomes more cluttered so is there any clean way to do this.

      Comment

      Working...