Javascript code loading Optimization Method

Source: Internet
Author: User

The following example shows a simpler method:

Save the Statistical Code to one file: file path:/config/counter. conf.

The Statistical Code is as follows:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var _ gaq = _ gaq | [];
_ Gaq. push (['_ setaccount', 'ua-18744406-1']);
_ Gaq. push (['_ trackpageview']);

(Function (){
Var ga = document. createElement ('script'); ga. type = 'text/javascript '; ga. async = true;
Ga. src = ('https: '= document. location. protocol? 'Https: // ssl ': 'http: // www') + '.google-analytics.com/ga.js ';
Var s = document. getElementsByTagName ('script') [0]; s. parentNode. insertBefore (ga, s );
})();

</Script>

We use StreamReader to read the file content, and the code will not be listed in detail.

We need a page to output this javascript code:

Page:/do. ashx? Args = GetCounter
Copy codeThe Code is as follows:
String code = "read statistical code ";
Code = Regex. Replace (code, "[\ ']", "\" ");
Code = Regex. Replace (code, "[\ n \ r]", "");
Context. Response. Write ("document. write ('" + code + "');");

In this way, the output javascript can be added to the page to implement the statistical function!

You only need to add the following code to the javascript file referenced on the webpage:
Copy codeThe Code is as follows:
Var _ s = document. createElement ('script ');
_ S. type = 'text/javascript ';
_ S. src = '/do. ashx? Args = GetCounter ';
Var _ fs = document. getElementsByTagName ("script") [0];
_ Fs. parentNode. insertBefore (_ s, _ fs );

As a result, the statistical code is not displayed on your webpage, but has actually been loaded to Your webpage!

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.