1

I was reading the book : Third party Javascript :

There was a sample code : (load external js)

  (function ()
    {
        var script = document.createElement('script');
        script.async = true;
        script.src = 'js_file.js';
        script.onload = script.onreadystatechange = function ()
        {
            var rdyState = script.readyState;
            if (!rdyState || /loaded|complete/.test(rdyState))
            {
                /*...*/
                script.onload = null;
                script.onreadystatechange = null;
            }
        };
        var entry = document.getElementsByTagName('script')[0];
        entry.parentNode.insertBefore(script, entry);
    })();

I'm trying to understand that line :

if (!rdyState || /loaded|complete/.test(rdyState))...

I'm getting undefined in script.readyState

enter image description here

Questions :

  • Why am I getting undefined in script.readyState ?
  • Should readystate return numbers or strings ? accoring to the regex test it suppose to return strings. but Ive seen many places where it returns numbers. so... ?

http://jsbin.com/ipOrIDeY/4/edit

(chrome 31. thanks Google but no thanks for the font smoothing version.(32))

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • Seems the same problem [here](http://stackoverflow.com/questions/1929742/can-script-readystate-be-trusted-to-detect-the-end-of-dynamic-script-loading) – guy777 Dec 10 '13 at 11:10
  • @guy777 The answer there talks about onreadystate never gets called . but onload does..... **which makes me ask** : does readyState is set only when the onreadstate is called ? – Royi Namir Dec 10 '13 at 11:11

1 Answers1

2

Here is my code to load javascript files,it works very well,readystate returns string,but it's value depends on your javascript engine.

 var n = document.createElement('script');
          n.setAttribute('type', 'text/javascript');
          n.setAttribute('src', 'Your src');
          n.setAttribute('async', true);
          n.onerror = function() {
            callback()
            n.onerror = null;
          };

          n.onload = n.onreadystatechange = function() {
            if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
              callback()
              n.onload = n.onreadystatechange = null;
            }
          };

          document.body.appendChild(n);
yoyo
  • 722
  • 6
  • 4
  • I think readyState not working on Chrome or Firefox. [Here's a solution](http://web.onassar.com/blog/2011/04/07/readystate-firing-for-dynamically-loaded-scripts/) – guy777 Dec 10 '13 at 11:37