Ratan Kumar
Ratan Kumar

Reputation: 1650

why requirejs is not loading Dependencies?

after reading this hack

which cleared the concept of making jquery load before the dependencies. I tweaked it for requrejs . console gives no error. but both js files are getting loaded (fyjsfies) .

but not the requrejs dependencies .

i made my code something like this ..

(function (window, document, callback) {
  var j, d;
  var loaded = false;
  if(!(j = window.require) || callback(j, loaded)) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "full_https_path_myjsfile.js";
    script.onload = script.onreadystatechange = function () {
      if(!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
        callback((j = window.require).noConflict(1), loaded = true);
        j(script).remove();
      }
    };
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = "myjsfile.js";
    $("#someElement").append(script);
  }
})(window, document, function ($, require_loaded) {
  // Widget code here
  alert('i m here');
  require(["jquery", "model2", "model3", "model4"], function ($, model1, model2, model3) {});
});

alert is not being called why ???

Upvotes: 0

Views: 321

Answers (2)

Ody
Ody

Reputation: 2047

The problem is that the require script is added to the DOM but not loaded. Hence the onReadyStateChanged is not fired. to fix this, use document.documentElement.childNodes[0].appendChild(script) instead

Upvotes: 0

Joseph
Joseph

Reputation: 119827

You don't need this hack to load jQuery or anything else for that matter. You can configure RequireJS to alias dependencies to a path, especially those dependencies that are not formatted for RequireJS.

require.config({
  paths : {
    'jQuery' : 'path/to/jQuery.min.js'
  }
});

require(['jQuery'],function($){
  //jQuery is loaded
  //$ is either the global jQuery or jQuery if it was AMD formatted
});

Upvotes: 2

Related Questions