How to load JS of google-analytics (or another third-party)

Source: Internet
Author: User

After registering ga, ga will generate a js script. Many people directly copy this js file to the end of the <body> file (including blog, CSDN, and BlogJava ). But is the JS automatically generated by ga the most reasonable?

How is it reasonable? How is it unreasonable? Because ga is only an analysis tool, its use cannot affect our program. If it affects, it is unreasonable. It is reasonable.

Current ga usage:
Let's take a look at the js script automatically generated by ga, as shown below:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var gaJsHost = ("https:" = document. location. protocol )? "Https: // ssl.": "http: // www .");
Document. write (unescape ("% 3 Cscript src = '" + gaJsHost + "google-analytics.com/ga.js'type = 'text/javascript' % 3E % 3C/script % 3E "));
</Script>
<Script type = "text/javascript">
Try {
Var pageTracker = _ gat. _ getTracker ("UA-123456-1 ");
PageTracker. _ trackPageview ();
} Catch (err) {}</script>

Read this code and use document. write to load JS. Note that loading js is blocked, that is, this js is not fully loaded, and all subsequent resources and JS cannot be downloaded and executed. You may feel that this piece of code is at the end of the body, and there is no content, and nothing will block it.
Some others are ignored. I believe many people need to execute JavaScript or AJAX after loading the page when writing JS, which is generally written in window. onload event, or $ (document) written to jquery ). ready () method. These JS will be blocked. If we use AJAX to load a lot of data on our page in window. onload, ga cannot be accessed for some reason (harmony and Harmony), or the access is slow. The problem is that our own JS has been waiting for the loading of ga's JS, and will only execute our js after ga's JS loading times out.

Instance:
The following code uses jquery to send an ajax request (request 126.com) in document. ready ). Modify the host file before testing to make ga js unable to load:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Copy codeThe Code is as follows:
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"> </script>
<Script type = "text/javascript">
$ (Document). ready (function (){
$. Get ("http://www.126.com /");
});
</Script>
</Head>
<Body>
<Script type = "text/javascript">
Var gaJsHost = ("https:" = document. location. protocol )? "Https: // ssl.": "http: // www .");
Document. write (unescape ("% 3 Cscript src = '" + gaJsHost + "google-analytics.com/ga.js'type = 'text/javascript' % 3E % 3C/script % 3E "));
</Script>
<Script type = "text/javascript">
Try {
Var pageTracker = _ gat. _ getTracker ("UA-123456-1 ");
PageTracker. _ trackPageview ();
} Catch (err) {}</script>
</Body>
</Html>

Monitoring Chart:

It can be seen that ga cannot load. After 20 seconds of timeout, we will execute our ajax request. Our ajax request will only take 0.173 s, but it will wait 20 s.
Rational use of ga:

To use ga properly, two problems need to be solved:
1. How to load ga js,
2. How to immediately execute var pageTracker = _ gat. _ getTracker ("UA-123456-1"); pageTracker. _ trackPageview (); Code after ja loading of ga.

There are two main methods for loading js without blocking:
1. dynamically create <script tag
2. Use new Image (). src = "". This method only downloads JS and does not parse JS. Therefore, after loading js with this method, the functions in it cannot be called (this method is generally used for pre-loading ).

Complete code:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var gaJsHost = ("https:" = document. location. protocol )? "Https: // ssl.": "http: // www .");
Var head = document. getElementsByTagName ("head") [0] | document.doc umentElement;
Var script = document. createElement ("script ");
Script. src = gaJsHost + "google-analytics.com/ga.js ";

Var done = false; // prevents onload and onreadystatechange from being executed simultaneously
// Execute after loading to adapt to all browsers
Script. onload = script. onreadystatechange = function (){
If (! Done &&(! This. readyState | this. readyState = "loaded" | this. readyState = "complete ")){
Done = true;
Try {
Var pageTracker = _ gat. _ getTracker ("UA-123456-16 ");
PageTracker. _ trackPageview ();
} Catch (err ){}
Script. onload = script. onreadystatechange = null;
}
};
Head. insertBefore (script, head. firstChild );
</Script>

The above code is modified from jquery's ajax code. The above code is easy to understand. dynamically create a script to load js, and execute the code after loading through the onload or onreadystatechange event. After the code is modified, the monitoring test is as follows. The figure shows that ga is loaded for 20 s, but our ajax request is not executed after 20 s, but is executed immediately. JQuery loading ga:You may think that the above Code is too much to write, which is complicated. If you use jquery, You can simplify it as follows:
Copy codeThe Code is as follows:
Var gaJsHost = ("https:" = document. location. protocol )? "Https: // ssl.": "http: // www .");
$. GetScript (gaJsHost + "google-analytics.com/ga.js", function (){
Try {
Var pageTracker = _ gat. _ getTracker ("UA-123456-16 ");
PageTracker. _ trackPageview ();
} Catch (err ){}
});

For more information, see high-performance WEB development series.

For [Declaration] reprinted, please indicate the source: http://www.cnblogs.com/bearstar /. Commercial use prohibited!

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.