2

Ok, I feel a bit dumb having to ask this. There are any number of hits on similar questions, but I can't seem to get it right. If I modify the DOM via jQuery/Ajax, when is a loaded script actually parsed/executed?

The code below works on F/F, but not on Chrome or Opera. 'Working' means that it executes 'do_init()' without error. The loaded script (actually an svg file; 'file.svg') defines a number of vars which are required by 'do_init()' (which is in the 'static' script). These vars are visible to F/F, but not to Chrome or Opera ("variable xxx is undefined"). The file/script is correctly loaded into the DOM in all 3 cases, and contains an <svg>, with a <script> inside it.

I can get this to work (the svg displays) in Opera (or break in F/F) by re-arranging code, but not in Chrome. Using .success and .complete makes no difference.

Thanks.

<head>
...
<script type="text/javascript" src="do_init.js"></script>          
<script type="text/javascript"><![CDATA[
jQuery(document).ready(function() {
   ...
   $("#submit").click(function(e){
      e.preventDefault();
      var jqxhr =
         $("#svg").html(ajax_load).load("file.svg", function(response, status, xhr) {
            if(status == "error") {
               var msg = "Error: ";
               $("#error").html(msg + xhr.status + " " + xhr.statusText);
            } else {
               do_init(); // Ok in F/F, not in Chrome/Opera
            }
      });
   });
});
]]></script>
</head>
<body>
<button id="submit" type="button">Click Me!</button>
<div id="svg"></div>
</body>

EDIT 1

It turns out that they're never executed - at least in IE9, FF8, Chrome, Opera, and Safari. They are executed in FF7. I've just written a minimal test page which does an Ajax load of a script which is just an alert. This only shows an alert in FF7. I've also tried the script wrapped in an <svg>, which makes no difference.

EML
  • 9,619
  • 6
  • 46
  • 78
  • You may want to try using $.get() instead of load(). While the jQuery documentation claims that scripts are executed unless you give load() a target, I've had trouble loading scripts using load() that I didn't have using $.get() – Dave Nov 08 '11 at 16:00
  • I've just tried get instead, but I'm having trouble loading the DOM with the response - this is easy with load. I'll post back if I can load the DOM and see if it makes a difference... – EML Nov 08 '11 at 18:00

1 Answers1

2

This is part of the reason why it is recommended that you locate javascript at the end of the document, at the end of the body.

Generally, javascript is executed as it is encountered; if you put it at the top of the document, it will run early in the load process, late if located at the end. However, when using a library's "onLoad" or "domReady" functionality, you're deferring execution until a later time.

See the jQuery docs for more information: http://api.jquery.com/ready/

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

EDIT I misread the details of your question. A dynamically loaded script is parsed immediately, but the onLoad event may (or may not!) be fired in accordance with the HTTP transport aspect of the loaded script rather than upon the interpretation of the loaded script. Usually, this is fine (though some browsers don't reliably fire the event - IE, looking at you), but the timing you're after is not when the script has been fetched, but when it is actually parsed and active. These should be within milliseconds, usually rendering the difference meaningless.

There are some varying takes on solving issues with this technique, some of which are discussed here and here - none seem to specifically mention Chrome as a source of troubles though. That said, the suggested approach of polling for the included script (via a timeout) seems to be the least failure-prone of the suggestions, though it is also the solution I like least.

Chris Baker
  • 49,926
  • 12
  • 96
  • 115
  • I'm not really sure that this is relevant though. As far as I can make out, the ready and load events are only relevant when the doc is initially loaded. Once the event has fired that's it - I don't think they're of any value for later dynamically-loaded scripts. Or are they? – EML Nov 08 '11 at 17:58
  • Thanks Chris - just going through that now. Meanwhile, I've made an interesting observation, added as edit #1 above. – EML Nov 08 '11 at 21:09
  • I think you're right - getScript is the way to go. I've had to re-arrange everything to make sure that the Ajax call only gets a script, and no DOM stuff, and I've put the do_init call at the end of the loaded script, and that all works consistently. Thanks. – EML Nov 10 '11 at 17:44