Why is Twitter passing the lines of the JS fragment snippet to it?

Below is the snippet of the Twitter script download that you use to add the Tweet button to the web page.

!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"); 

On the last line, they pass the "script" into the IIFE arguments, rather than just declaring it as a variable.

What is the advantage of this? Is it easy to keep a couple of characters per code length?

+4
source share
1 answer

If they used a variable outside of IIFE, this could interfere with the variables of 10,000 human javascript on 10,000 human web pages. If there was already a variable with the same name, their inclusion on the page could interfere with work, and people would say: "I tried to use Twitter, but it broke my web page." Whether true or not.

Doing this the way they did leaves as little impact on the surrounding code as possible.

Variable inside

If they put the variable inside, it would be harder to document what should be added to an already working web page. They would need to teach the new javascript user how to format string variables, and the new guys would have to enter their information in two places in the code.

Thus, they should show only all lines, and the last - as "magic". β€œCopy these lines into,” they say.

They then explain that you must put the names of two things in quotation marks on the last line. It is easier to explain.

Admittedly, this is not much easier. But it’s a little easier to explain the times when thousands of people using it could increase market penetration, so to speak.

-2
source

All Articles