使用自定义UID加载通用脚本

时间:2014-01-24 14:04:51

标签: javascript ajax

我想为用户提供一个片段,用于放置他们自己的网站,这些网站会加载一个具有该用户唯一ID的通用javascript文件。这是加载的内容取决于与之关联的用户ID。

到目前为止,我最好的猜测是这样的:

<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>

我对这段代码运气不错。谁能解释我应该如何接近这个呢?

2 个答案:

答案 0 :(得分: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>

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

答案 1 :(得分: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");