Pregunta

Hey hope someone can help explain why these examples from Facebook's and Twitter's JS API asynchronous function calls are different and what their nuances represent perhaps in performance.

(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); 
    js.id = id;
    js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
    fjs.parentNode.insertBefore(js,fjs);
}(document, 'script', 'facebook-jssdk'));

!function(d,s,id){
    var js,fjs=d.getElementsByTagName(s)[0];
    if(!d.getElementById(id)){
        js=d.createElement(s);
        js.id=id;
        js.src="//platform.twitter.com/widgets.js";
        fjs.parentNode.insertBefore(js,fjs);
    }
}(document,"script","twitter-wjs");

As you can see one starts with the structure (){}(); and the other is !

I wonder if either is better.

Also I'm trying to load in 5 social network buttons at once and am trying this method for performance, any suggestions would be appreciated:

(function(d, s) {
var j, h = d.getElementsByTagName(script)[0],
    f = d.createDocumentFragment(),
    add = function(u, i) {
        if (d.getElementById(i)) {
            return;
        }
        j = doc.createElement(s);
        j.src = u;
        i && (j.id = i);
        f.appendChild(j);
    };

    add('http://apis.google.com/js/plusone.js');
    add('http://connect.facebook.net/en_US/all.js#xfbml=1', 'facebook-jssdk');
    add('http://platform.twitter.com/widgets.js', 'twitter-wjs');
    add('http://platform.linkedin.com/in.js');
    add('http://assets.pinterest.com/js/pinit.js');


    h.parentNode.insertBefore(f, h);
}(document, 'script'));
¿Fue útil?

Solución

It's just two different ways of writing an IIFE. There's no effective difference.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top