3

When using Head.js, and setting the .src attribute of a script element, there is callback method that is called when the script is ready.

However, I wanted to load a script by assigning text to .innerHTML. When doing this the same callback did not fire when I updated/edited the code to use this property instead.

/*addScriptText1
** modified from head.js
**
**
*/
function addScriptText1(file_name, callback, key) {
    var element = document.createElement('script');
    element.async = true;
    element.innerHTML = localStorage[file_name];
    element.onreadystatechange = element.onload = function () {
        $A.log('callback for element called');
        if ((!element.readyState || /loaded|complete/.test(element.readyState))) {
            localStorage[key + '_loaded'] = true;
            callback();
        }
    };
    document.head.appendChild(element);
}

2 Answers2

1

Scripts are executed immediately when inline scripts are inserted into the DOM. This all happens synchronously, so you don't need a callback.

async has no effect here because you are not doing a network request. Similarly, the readyState is not useful because you are creating it programatically, so the script is going to be immediately loaded.

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • @pure_code It does take time, but during that time the JS is blocked, so it is synchronous. – loganfsmyth Jan 02 '13 at 00:36
  • @pure_code Can you elaborate more on why you want/expect this to be asynchronous? – loganfsmyth Jan 02 '13 at 00:47
  • Yeah, it is single-threaded, so at best allowing it to be asynchronous would allow parsing of the script to run in parallel with your application logic, but at the end of the day parsing is not what takes up the most time. – loganfsmyth Jan 02 '13 at 01:18
  • technically, worker threads could be use to interpret Dom-independent scripts in parallel. –  Mar 09 '13 at 21:59
  • @pure_code Yep, WebWorkers can load scripts in the background and use message passing, but that was not your question. – loganfsmyth Mar 09 '13 at 22:06
  • for those that might sub-consciously over-generalize the answer I have provided a pre-emptive note. :) –  Mar 09 '13 at 22:09
1

Using innerHTML on a script element is not supported cross-browser (including Firefox iirc). I would not recommend this approach. I would suggest eval or new Function instead.

Can scripts be inserted with innerHTML?

Community
  • 1
  • 1
mwilcox
  • 4,065
  • 23
  • 20