Royi Namir
Royi Namir

Reputation: 148534

Loading asynchronous JS file & readyState?

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 :

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

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

Upvotes: 1

Views: 2637

Answers (1)

yoyo
yoyo

Reputation: 722

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);

Upvotes: 2

Related Questions