Shortest javascript: loading script code in the address bar _ javascript tips-js tutorial

Source: Internet
Author: User
I believe that all of you have executed scripts in the address bar in the form of javascript. This method is simple and practical. It is often used to test short scripts, but it is not long enough to copy a large segment to the address bar, it is not easy to modify the script. Therefore, you should first write the script in a separate file, and then dynamically load the script to the page in the form of javascript. Many Web plug-ins use this method to load.

In normal times, we use the simplest code to implement dynamic loading:

The Code is as follows:


Javascript: var o = document. createElement ('script'); o. src = '...'; document. body. appendChild (o); void (0)


Of course, this is OK enough for loading the plug-in. But not long ago I saw a slightly modified method, so I began to wonder how short the code can be compressed!
His code is roughly the same, but more rigorous:

The Code is as follows:


Javascript :( function (o) {o. src = '... '; document. body. appendChild (o)}) (document. createElement ('script'); void (0)


Although the Code is longer than the previous one, the variable is placed in the closure to avoid potential conflicts. Document. createElement is used as the closure parameter, which cleverly saves a var word.
There is nothing to worry about, so consider whether the code can be simplified. By the way, I will review various features in js.
Of course, the following rules are followed by loading scripts in the address bar by default:
1. Do not introduce global variables
2. compatible with mainstream browsers
3. the loading process does not affect the page
> Global variables are not affected. We need to use closures to hide our private variables;
> Compatible with mainstream browsers, standard methods must be used. Compatibility judgment only increases the code length;
> If you simply use innerHTML to add elements, the existing elements may be refreshed;
So we began to analyze it gradually.
Obviously, the first thing that comes to mind is the call of the anonymous closure.
Generally, we call an anonymous closure in the form of (function. Note that red priority brackets are indispensable; otherwise, they are an incorrect syntax.
However, you can also use another form: + signs before + function () {} () can be changed -!~ And so on. However, this is only one byte difference.

Obviously, you can replace the void (0) parameter with the closure call expression. Although void is only a keyword, it has functions similar to functions. undefined is returned for any parameter. If there is no void, after javascript: is executed in the address bar, the page becomes the return value of the script expression. You should have seen it before.
  
As a result, after obvious observation, it is slightly reduced by 3 characters.

The Code is as follows:


Javascript: void (+ function (o) {o. src = '...'; document. body. appendChild (o)} (document. createElement ('script ')))


However, the above are all superficial observations. Now let's analyze it carefully.
  
The reason why we need to use closures is to prevent conflicts between our variables and pages. So can I not use variables? To avoid variables, you can use chained connections and other operations: Use the return value of the previous operation as the parameter of the next operation. The Code contains three operations: Create a script element, assign a value to the src element, and add a script element. For more information, see the W3C manual. DOM. appendChild can not only add elements, but also return values. The order in which src values are assigned and elements are added is interchangeable. Therefore, we can use chained operations to completely discard closures and variables:

The Code is as follows:


Javascript: void (document. body. appendChild (document. createElement ('script'). src = '...')


In this step, we have reduced the length by 19 characters!
  
We will continue to observe. The above Code contains two documents. We can reduce the number of words if we use a short variable instead. However, when variables are used, there will be a conflict, so closure will be used again... Recall that there is something in js that we do not recommend at ordinary times:. Yes, he can solve this problem. I only need with (document. Because there is only one line of code, you can remove the braces. Therefore, it is reduced by four characters:

The Code is as follows:


Javascript: with (document) void (body. appendChild (createElement ('script'). src = '...')


It is worth noting that void is no longer nested in the outermost layer, because with and if, for, they are no longer expressions, but statements.
  
At this point, every sentence in the Code is responsible for each other, and duplicate words cannot be found. Can we streamline it? If you want to find it, you have to find it from the void guy. If it is removed, the page becomes the src character of the script element after the address bar is executed. Obviously, it cannot be deleted. But we can try another one, such as alert. After the dialog box is displayed, the page is retained.
Previously, void only returns an undefined function, while alert does not. Javascript is different from other languages. In other languages, there are almost two concepts of functions/processes. A process is a function without return values. But javascript can be different. Any function in js has a return value. Even if "no return value" is returned, it is undefined. Therefore, alert and void share the same returned value: undefined. After the address bar is executed, the page will not jump, but other functions such as false, 0, null, and NaN will not work.
  
Therefore, we only need to make the expression return undefined, but it must be shorter than void. To generate an undefined, in addition to its literal constant, it also calls a function without return values, or accesses an attribute that does not exist in an object. We should be as short as possible. If jQuery is used in the page, we can use $. X to get an undefined. If jq is not used, the existence of variable $ cannot be guaranteed. Since we cannot find a brief global variable, we can use json to create an anonymous variable, such as [] or {}, and then access its non-existent attribute, such as []. X. So we can say goodbye to void:

The Code is as follows:


Javascript: with (document) body. appendChild (createElement ('script'). src = '...'; []. X


This reduces 1 byte. We can also merge the code and replace X with an expression:

The Code is as follows:


Javascript: with (document) [] [body. appendChild (createElement ('script'). src = '...']


This reduces 1 byte.
  
In fact, any variable in js inherits from the Object, even if the number is no exception. Therefore, we can replace [] with a number to further reduce the number by 1 character:

The Code is as follows:


Javascript: with (document) 0 [body. appendChild (createElement ('script'). src = '...']


At this point, in addition to the src characters, the code is shortened to 76 bytes.
  
Of course, the ultimate limit is still under exploration...
  
With Google's short Domain Name Service Google URL Shortener, we can shorten the Script URL, for example:

The Code is as follows:


Javascript: with (document) 0 [body. appendChild (createElement ('script'). src = 'HTTP: // goo. gl/qpp29']

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.