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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//------------------------------------------------------------------------------------------------
// 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:

1
2
3
4
if (!included('my-file.js'))
{
    // TODO...
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//------------------------------------------------------------------------------------------------
// 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:

1
2
3
4
5
6
7
8
9
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//------------------------------------------------------------------------------------------------
// 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:

1
2
3
4
5
6
if (loadscript('my-file1.js'))
{
    //TODO...
}
 
loadscript('my-file2.js', true);

No hay comentarios:

Publicar un comentario