Mootools Request.HTML returns undefined

266 views Asked by At

I am loading Mootools dynamically in the scripting part of an app (AutoWWW) because it does not allow direct HTML usage.

I am using Request.HTML and want to get the html of a page but it returns an 'undefined' message. How can i fix this?

My code:

function loadScript(url, callback) {
    // Adding the script tag to the head as suggested before
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}

var mootools = new Request({
    url: 'http://google.com',
    method: 'get',
    onSuccess: function(responseText){
        alert(responseText);
    }
});

loadScript("https://ajax.googleapis.com/ajax/libs/mootools/1.6.0/mootools.min.js", mootools);
1

There are 1 answers

2
Sergio On BEST ANSWER

There are 2 things you should take into account. One is possible CORS limitations, the other is that when you do head.appendChild(script); it will load the script asynchronously.

This means MooTools will be loaded but it will not be available until the callback function is called. To fix this you should have the callback internally inside the loadScript function, and from inside that callback call the other callback that was passed as function argument.

function loadScript(url, callback) {
  // Adding the script tag to the head as suggested before
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';

  script.onreadystatechange = callback;
  script.onload = function() {
    new Request({
      url: 'https://jsonplaceholder.typicode.com/posts/1',
      method: 'get',
      onSuccess: callback
    }).send();
  };
  script.src = url;

  head.appendChild(script);
}

loadScript("https://ajax.googleapis.com/ajax/libs/mootools/1.6.0/mootools.min.js", function(text) {
  alert(text);
});