viernes, 28 de junio de 2013

Inclusiones dinámicas de scripts en JavaScript

Verifica si ya se incluyó un script (en la sección de cabecera por defecto):

//------------------------------------------------------------------------------------------------
// Engines      JavaScript 1.2+
//              JScript    3+
// Environments NN6+ IE5+ MOZILLA1+ SAFARI1+
// DOM Level    1 Core
//------------------------------------------------------------------------------------------------
function included (s /* scr */, t /* tag-name (head by default) */)
{
    var d;
    if (!t) t = 'head';

    if (typeof s == 'string' && (d = s.indexOf('../')) != -1)
        s = s.substr(d + 3);

    d = document;
    t = d.getElementsByTagName(t);

    for (var i = 0, l = t.length, e; i < l; ++i)
    {
        e = t[i].getElementsByTagName('script');

        for (var j = 0, n = e.length; j < n; ++j)
            if (e[j].src && (s.test ? s.test(e[j].src) : e[j].src.lastIndexOf(s) != -1))
                return true;
    }

    return false;
}

Uso:

if (!included('my-file.js'))
{
    // TODO...
}

Incluye uno o varios scripts (en la sección de cabecera por defecto):

//------------------------------------------------------------------------------------------------
// Engines      JavaScript 1.2+
//              JScript    3+
// Environments NN6+ IE5+ MOZILLA1+ SAFARI1+
// DOM Level    1 Core
//------------------------------------------------------------------------------------------------
function include (/* arg1 [, ... [, argN]] */)
{
    var r = '', x = r;
    for (var d = document, i = 0, a = arguments, l = a.length, e, s; i < l; ++i)
    {
        if ((s = a[i]).root && (r = s.root + '').length > 0 && r.lastIndexOf('/') != r.length - 1)
            r += '/';
   
        if (s.extension && (x = s.extension + '').length > 0 && x.indexOf('.') != 0)
            x = '.' + x;

        if (s.src || typeof s == 'string')
        {
            e = d.createElement('script');
            e.setAttribute('src',  r + (s.src ? s.src : s) + x);
            e.setAttribute('type', s.type ? s.type : 'text/javascript');

            if (typeof s.onload == 'function')
            {
                if (e.readyState) 
                {
                    e.onreadystatechange = function ()
                    {
                        if (this.readyState == 'loaded' || this.readyState == 'complete')
                        {
                            delete this.onreadystatechange;
                            this.loaded();
                        }
                    }

                    e.loaded = s.onload;
                }
    
                else e.onload = s.onload;
            }

            d.getElementsByTagName(s.tag ? s.tag : 'head')[0].appendChild(e);
        }
    }
}

Uso:

if (!included('my-file1.js') && !included('my-file2.js')) include
(
      {root: 'my-path', extension: 'js'}
    , {src: 'my-file1', onload: function () { /* TODO... */ }}
    , {src: 'my-file2', onload: function () { /* TODO... */ }}
);

if (!included('my-file4.js'))
    include({src: 'my-file4.js', onload: function () { /* TODO... */ }});

Existe otro modo de hacerlo, usando ajax:

//------------------------------------------------------------------------------------------------
// Engines      JavaScript 1.2+
//              JScript    3+
// Environments NN7.1+ IE5+ MOZILLA1+ SAFARI1.2+
//------------------------------------------------------------------------------------------------
function loadscript (s /* url */, b /* eval? (Boolean) */)
{
    var r, x, w = window;
 
    if (w && w.XMLHttpRequest)
        r = new w.XMLHttpRequest();
 
    else if (typeof Components != 'undefined' && Components.classes)                               // XPCOM!
    {
        try
        {
            r = Components.classes['@mozilla.org/xmlextras/xmlhttprequest;1'].createInstance
            (
                Components.interfaces.nsIXMLHttpRequest
            );
        }
   
        catch (e)
        {
            r = null;
        }
    }
 
    else if ((x = w.ActiveXObject) || (x = w.GeckoActiveXObject)) 
    {
        try
        {
            r = new x('Msxml2.XMLHTTP');
        }
  
        catch (e)
        {
            try
            {
                r = new x('Microsoft.XMLHTTP'); 
            }

            catch(e)
            {
                r = null;
            }
        }
    }
 
    if (r)
    {
        r.open('GET', s, false);
        r.send(null);
  
        if (r.readyState == 4 && r.status == 200)
        {
            if (b) eval(r.responseText);
            else
            {
                (w = (x = document).createElement('script')).setAttribute('type', 'text/javascript');
                w.text = r.responseText;
                x.getElementsByTagName('head')[0].appendChild(w);
            }

            return true;
        }
    }
    
    return false;
}

Uso:

if (loadscript('my-file1.js'))
{
    //TODO...
}

loadscript('my-file2.js', true);

No hay comentarios:

Publicar un comentario