这个脚本做什么用的?

时间:2015-12-08 04:38:47

标签: javascript html5 css3

我是JavaScript新手,无法理解这个嵌入式脚本。有人可以向我解释一下代码的含义及其工作原理吗?非常感谢您的时间和帮助!!

<body>
    <div class="trapdoor">
        <div class="top door">
        </div>
        <div class="bottom door">
        </div>
        <a href="https://twitter.com/twholman" 
           class="twitter-follow-button" 
           data-show-count="false" 
           data-size="large" 
           data-dnt="false">
            Follow @twholman
        </a>
        <script>!function (d, s, id) {
                var js, fjs = d.getElementsByTagName(s)[0];
                if (!d.getElementById(id)) {
                    js = d.createElement(s);
                    js.id = id;
                    js.src = "http://platform.twitter.com/widgets.js";
                    fjs.parentNode.insertBefore(js, fjs);
                }
            }(document, "script", "twitter-wjs");
        </script>
    </div>
</body>

4 个答案:

答案 0 :(得分:1)

如前所述,此功能加载Twitter小部件。这是一个快速的脏话解释。

// shorthand for a self-invoking function that accepts 3 named arguments
!function (d, s, id) { 

    // defines 2 variables, the second being the first "s" element 
    // in the document (zero-based index)
    var js, fjs = d.getElementsByTagName(s)[0]; 

    // checks whether the element with passed-in ID doesn't exist
    if (!d.getElementById(id)) { 

        // if not, create it
        js = d.createElement(s); 

        // assign the earlier argument as an ID property of the element
        js.id = id; 

        // define the source property of the element
        js.src = "http://platform.twitter.com/widgets.js"; 

        // add the element to the document
        fjs.parentNode.insertBefore(js, fjs); 
    }

// name and scope the function
}(document, "script", "twitter-wjs");

答案 1 :(得分:1)

它与:

相同
<script>

//If the twitter SCRIPT element doesn't exist in the document yet...
if(!document.getElementById('twitter-wjs'))
{
    //Make a new script element
    var s=document.createElement('script');
    //set its id so we know it exists after we insert into the document
    s.id='twitter-wjs';
    //the external script we want to run
    s.src='http://platform.twitter.com/widgets.js';
    //The first script block in the document, which could be this one
    var firstScript=document.getElementsByTagName('script')[0];
    //Now we insert our new external script before the first script in the document
    firstScript.parentNode.insertBefore(s, firstScript);
}
</script>

除了它不会污染文档中的全局变量,因为它是一个自运行函数。

答案 2 :(得分:1)

它是用三个参数文档和字符串调用的自调用函数&#34; script&#34; &安培; &#34;与Twitter WJS&#34 ;.如果&#34; twitter-wjs&#34;在文档中找不到id,它创建 脚本标签与src&amp; id&amp;将脚本插入脚本标记列表中。

答案 3 :(得分:0)

如果不存在id为twitter-wjs的脚本,则插入一个带有src equels http://platform.twitter.com/widgets.js的脚本。而且它是自我执行的。