2014-01-24 36 views
0

我想給用戶一個片段,以便將自己的網站加載一個通用JavaScript文件併爲該用戶提供唯一的ID。這是如此加載的內容取決於哪個用戶ID與它相關聯。使用自定義UID加載通用腳本

我最好的猜測,到目前爲止是這樣的:

<script type="text/javascript"> 
    var UID = ''; 

    (function() { 
     var url = www.test.com/embed.js'; 
    })(); 
</script> 
<noscript>Please enable JavaScript to view this content</noscript> 
<a href="http://www.test.com" class="link">content powered by <span class="logo">Test</span></a> 

我還沒有有很多的運氣與此代碼。任何人都可以解釋我應該如何接近這個?

+0

什麼是對每個用戶的唯一ID的目的是什麼? – user1477388

+0

顯示由AJAX加載的不同內容 –

回答

1

這是谷歌做它的方式。讓我知道如果您需要幫助應用它:

<script type="text/javascript"> 

    var _gaq = _gaq || []; 
    _gaq.push(['_setAccount', 'UA-XXXXX-X']); 
    _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> 

Ref。 https://developers.google.com/analytics/devguides/collection/gajs/

1
  1. 您需要將<script>標籤附加到DOM。
  2. 你應該把你的整個腳本一個單一的範圍內(功能)

    (function(window, uid) { 
        var document = window.document; 
    
        // create your <script> element 
        var e = document.createElement("script"); 
        e.src = "//my.website.com/my-script.js?user-id=" + window.encodeURIComponent(uid); 
    
        // insert it before the very first <script> element already in DOM 
        var s = document.body.getElementsByTagName("script")[0]; 
        s.parentNode.insertBefore(e, s); 
    })(window, "some-user-id"); 
    
相關問題