Search code examples
javascriptdojogoogle-closuregoogle-closure-library

dynamic script tag loading is not working as expected


We have an application that uses both the google closure and dojo libraries. We have the following in our index page which works as expected:


<script type="text/javascript" src="runtime/src/lib/google-closure-rev26/closure/goog/base.js"></script>
<script type="text/javascript" src="runtime/src/lib/dojo_release_132_src/dojo/dojo.js"></script>
<script type="text/javascript" src="runtime/src/core/loader.js"></script>

We would like to use only one script tag in the actual html source. So we tried to do the following:


<head>
   <script type="text/javascript" src="runtime/src-bootstrap.js"></script>
</head>

and then in src-bootstrap.js:


var head = document.getElementsByTagName("head")[0];

var s1 = document.createElement("script");
s1.type = "text/javascript";
s1.src = "runtime/src/lib/google-closure-rev26/closure/goog/base.js";


var s2 = document.createElement("script");
s2.type = "text/javascript";
s2.src = "runtime/src/lib/dojo_release_132_src/dojo/dojo.js";

var s3 = document.createElement("script");
s3.type = "text/javascript";
s3.src = "runtime/src/core/loader.js";

head.appendChild(s1);
head.appendChild(s2);
head.appendChild(s3);

However, this doesn't work in FF. core/loader.js runs before dojo is loaded completely. Any ideas why this doesn't work?


Solution

  • For this type of mechanism, you'd be better off using document.write() to include your scripts. The technique you're currently using is suited to lazy-loading scripts, and it downloads and executes the scripts asynchronously: http://www.nczonline.net/blog/2009/06/23/loading-javascript-without-blocking/

    ...or you could have a build process that actually concatenates these files, and just request the one script, which would save on the number of requests too, as what you've actually done is increased the number of requests.