Tuesday, April 2, 2013

Third Party Javascript

 Chapter 2. Distributing and loading your application
          ...
          Loading additional files

          The book recommends the following snippet of code load additional files from within your main third party script.

          function loadScript(url, callback) {
var script = document.createElement('script');

script.src = url
                script.async = true;

                var entry = document.getElementsByTagName('script')[0];

                entry.parentNode.insertBefore(script, entry);

                script.onload = script.onreadystatechange = function() {
               var rdyState = script.readyState;

                if(!rdyState || /complete|loaded/.test(script.readyState)) {
                callback();

               // Detach our handlers to avoid memory leaks
               script.onload = null;
               script.onreadystatechange = null;
        }
          }

          I created the following function to let me know once all the scripts have finished loading. Maybe you will find it useful as well.

          function loadSupportingFiles(callback) {
var i = 0;
var numberOfFiles = 0;

loadScript('http://camerastork.com/javascripts/util.js', scriptsDone());
loadScript('http://camerastork.com/javascripts/dom.js', scriptsDone());
loadScript('http://code.jquery.com/jquery-1.9.1.min.js', scriptsDone());

function scriptsDone() {
numberOfFiles++;

return function () {
i++;

if(i === numberOfFiles) {
callback();
}
};
}
}

          Passing script arguments



       
https://github.com/rhanak/thirdpartyjs

Taken from Third-Party JavaScript http://www.manning.com/vinegar/

No comments:

Post a Comment