3

I'd like to load an external JavaScript file, using jQuery, asynchronously, and then be able to call functions loaded from the external JavaScript. I'm including my JS file at the bottom of my html, just before </html>. The jQuery code is just before my code.

I'm trying this:

(function(){

    $(document).ready(function() {
        obj.init();
    });

    var obj = {

        init:function(){

            $.ajax({
                url: 'http://domain.com/script.js',
                dataType: 'script',
                success: function() {
                    obj.dostuff();
                }
            });

        },
        dostuff:function() {
            // ...do stuff
        }

    }
    window.obj = obj;

})();

The Chrome JavaScript console is reporting this:

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

I'm trying to keep all my JS in one file, all in objects (classes & functions style), and then call each class (an init() function) from within the $(document).ready();.

What am I doing wrong here..?

Matija Grcic
  • 12,963
  • 6
  • 62
  • 90
Stephen Last
  • 5,491
  • 9
  • 44
  • 85
  • 1
    You can check this: http://api.jquery.com/jquery.getscript/ and this: http://stackoverflow.com/questions/24297829/execute-write-on-doc-it-isnt-possible-to-write-into-a-document-from-an-asynchr – vaso123 Dec 17 '14 at 11:31
  • Thanks @lolka_bolka, I certainly can, and already have... `$.getScript()` is just shorthand for my `$.ajax()` call (so replacing `$.ajax()` with `$.getScript()` does not make my code example work), and that other stack question doesn't involve jQuery. My question relates to asynchronous JavaScript in the way my code shows. Do you know how to get `$.ajax()` to use a jQuery DOM insert rather than a `document.write`..? Like I said, I want to use jQuery to include external asynchronous JavaScript in the way my code shows. – Stephen Last Dec 17 '14 at 13:16

1 Answers1

4

You can load the script by using the following

var scriptElement = document.createElement('script');
scriptElement.src = "http://code.jquery.com/jquery-latest.min.js";
document.getElementsByTagName('head')[0].appendChild(scriptElement);

Then you can start using jQuery or whatever library you have loaded.

Or something similar

function loadMyScript() {
  var script = document.createElement('script');
  script.type = "text/javascript";
  script.src = "http://code.jquery.com/jquery-latest.min.js";
  document.body.appendChild(script);
}

window.onload = loadMyScript;

UPDATE:

(function(app, $, undefined) {

  //public
  app.init = function() {

    var url = "//code.jquery.com/color/jquery.color.js";
    $.getScript(url, function() {
      doStuff();
    });
  };

  //private
  var doStuff = function() {

    $(".block")
      .animate({
        backgroundColor: "rgb(255, 180, 180)"
      }, 1000)
      .delay(500)
      .animate({
        backgroundColor: "olive"
      }, 1000)
      .delay(500)
      .animate({
        backgroundColor: "#00f"
      }, 1000);
  };

}(window.app = window.app || {}, jQuery));
window.onload = app.init;

Here's the JsBin: http://jsbin.com/lumapubozu/1/edit?html,js,output

GOOGLE MAPS UPDATE

You just say in the link 'callback=app.loadMap' what it your callback.

(function(app) {

      app.loadMap = function() {
        var mapOptions = {
          zoom: 8,
          center: new google.maps.LatLng(-34.397, 150.644)
        };

        var map = new google.maps.Map(document.getElementById('map-canvas'),
          mapOptions);
      };

      app.loadGoogleMapsScript = function () {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
          'callback=app.loadMap';
        document.body.appendChild(script);
      };

    }(window.app = window.app || {}));

    window.onload = app.loadGoogleMapsScript;

JsBin: http://jsbin.com/wigoxarayu/1/edit?js,output

Matija Grcic
  • 12,963
  • 6
  • 62
  • 90
  • Thanks @Matija Grcic, but how do I use jQuery to asynchronously include external JavaScript in the way my code shows..? I don't want to start including JavaScript outside my object/class/function system. – Stephen Last Dec 17 '14 at 13:19
  • Thanks again! After looking at your example, I can see the issue is with the included external JS, rather than my code. You're including a jQuery colour extension, but I'm actaully trying to use the Google Maps API: `maps.googleapis.com/maps/api/js?key=xxxx`. This obviously includes a `document.write` where the colour extension doesn't - and my original code works just fine (and doesn't show the console error when including the colour extension). – Stephen Last Dec 17 '14 at 14:23
  • ...so it's not me, and it's not jQuery using the `document.write`, it's Google's API. Bugger. – Stephen Last Dec 17 '14 at 14:26
  • 1
    @CrusaderLtd You should have said it's Google Maps see the update. – Matija Grcic Dec 17 '14 at 15:04
  • you are quite right, I should have. I have marked your answer as accepted. I was trying to make my example code not dependent on any third-party code, so I could use it again for including other external JS - because I thought the issue was with my code. – Stephen Last Dec 17 '14 at 15:14