Supposedly, you're supposed to put the script at the beginning or the end of the body, outside of any form tags. My method puts it right after the opening body tag.
One method of injecting something to a specific part of the page involves overriding the Page Render method, rendering the HTML, searching for the place in the HTML you want to put the script, inserting it, then writing out the HTML. That works, but it's clunky.
Here's how I do it:
- In the OnPreRender event in a page class, after base.OnPreRender(e); I put this: ScriptWriter.WriteGoogleAnalyticsScript(this); I have a class called ScriptWriter and a static method called WriteGoogleAnalyticsScript that takes a System.Web.UI.Page as a parameter.
- I've included my code for WriteGoogleAnalyticsScript here.
- What the method does is writes my own script to the page using ClientScript.RegisterStartupScript() which writes the script before the closing Form Tag. The script depends on a setting in your web.config called GOOGLE_ANALYTICS_CODE. If the analytics code doesn't exist, it will throw an error telling you that it's missing. You get the actual analytics code from the Google folks using their Google Analytics site.
- My Javascript dynamically creates the necessary script nodes for the Google Analytics and inserts them into the DOM right after the opening body tag (where I wanted them).
- Using Firebug, you can see the change in the DOM. If you choose View-Source in your browser you will not see the code; you'll only see the HTML that was received from the server.
You'll notice a setTimeout() call in the Javascript before inserting the 2nd script into the DOM. This was needed to make IE happy. Firefox was fine without that.
I had fun figuring this out, and I hope you find it useful.
0 comments:
Post a Comment