javascript - jQuery script execution order in html injection -
consider following js code:
var html = '<script>$("body").append("a");</script>' + '<script src="script.js"></script>' + '<script>$("body").append("c");</script>'; $("body").append(html);
and assume script.js contains following:
$("body").append("b");
it seems that, indeed, "a", "b" , "c" appended body (in order). and, obviously, "c" appended body after script.js
has finished loading (so, example, if takes 5 seconds script.js
finish loading "c" appended body after 5 seconds).
my question following: can rely on behavior in jquery? deterministic or may encounter unpredictable situations?
this useful in terms of dynamically loading scripts make use of .js files not loaded yet. can assume script.js contains function f(){}
, third line have been <script>f()</script>
. if same order scripts loading/execution there no issues, otherwise may experience f not defined
exception (if tag executed before loading script.js file).
this isn't jquery specific behavior as browser behavior. when loading scripts pre-defined in document, loaded in order or appearance. same not true when dynamically append script tag document.
if loaded javascript files show, start download the external file when source of element set dom.
example:
script in head of html file
$(function() { var html = '<script>$("body").append("a");<\/script>' + '<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"><\/script>' + '<script>$("#my-dialog").dialog();<\/script>'; $("body").append(html); }
body element of html file
<div id="my-dialog"> content here </div>
the above code wouldn't execute expect. a
appended body , jquery.ui
loaded , dialog
appear, in fact third script fail because jqueryui hasn't finished downloading , has yet parsed. if typed $("#my-dialog").dialog();
console, there wouldn't issues since file downloaded , parsed @ point.
this 1 of main reasons module loaders popular. tell requires , take care of loading them in needed order.
you can read more w3c spec scripts here.
Comments
Post a Comment