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'));
有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top