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..?

2
  • 1
    You can check this: api.jquery.com/jquery.getscript and this: stackoverflow.com/questions/24297829/… Commented Dec 17, 2014 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. Commented Dec 17, 2014 at 13:16

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

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.
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).
...so it's not me, and it's not jQuery using the document.write, it's Google's API. Bugger.
@CrusaderLtd You should have said it's Google Maps see the update.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.