asynchronous javascript loading/executing

后端 未结 4 450
萌比男神i
萌比男神i 2020-12-05 16:14

In this post, asynchronous .js file loading syntax, someone said, \"If the async attribute is present, then the script will be executed asynchronously, as soon as it is avai

4条回答
  •  情歌与酒
    2020-12-05 16:41

      (function(doc, script) {
        var js, 
            fjs = doc.getElementsByTagName(script)[0],
            add = function(url, id) {
                if (doc.getElementById(id)) {return;}
                js = doc.createElement(script);
                js.src = url;
                id && (js.id = id);
                fjs.parentNode.insertBefore(js, fjs);
            };
    
        // Google Analytics
        add(('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js', 'ga');
        // Google+ button
        add('https://apis.google.com/js/plusone.js');
        // Facebook SDK
        add('//connect.facebook.net/en_US/all.js', 'facebook-jssdk');
        // Twitter SDK
        add('//platform.twitter.com/widgets.js', 'twitter-wjs');
    }(document, 'script'));
    

    source: https://css-tricks.com/thinking-async/

提交回复
热议问题