How to trigger code once in a thank you page?
We do this by setting a flash message server side and then checking for this in the template. Flash messages are only shown once so no need to manually delete/unset. The best way to do this would be using a custom plugin that listens for the commerce_orders.onOrderComplete event:

&lt;?php
namespace Craft;

class FireAnalyticsPlugin extends BasePlugin
{
    function init()
    {
        craft()-&gt;on('commerce_orders.onOrderComplete', function($event) 
        {
            craft()-&gt;userSession-&gt;setFlash('successfulOrderPlaced', true);
        }
    }
}


Customer order page template:

{% if craft.session.getFlash('successfulOrderPlaced') %}
// Add Google Analytics here
{% endif %}