7

Google タグ マネージャー スクリプトを配置したいのですが、Google タグのドキュメントによると、スクリプトは開始タグの直後に配置する必要があります。

ソース コードを変更することはできないため、次のコード スニペットを使用してスクリプトを追加する必要があります。

<script type="text/javascript">
(function () {
    var url = "path/to/js/file";
    var gtm = document.createElement('script');
    gtm.type = 'text/javascript';
    gtm.async = true;
    gtm.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + url;
    var s = document.getElementsByTagName('body')[0];
    s.parentNode.insertBefore(gtm, s);
})();
</script>

Google アナリティクスのスクリプト スニペットとほぼ同じです。これで、body タグの直前にスクリプトが追加されました。jQueryメソッドinsertAfterを使用するのが適切な方法なのか、それとももっと良い方法があるのか​​ わかりません!

あなたの親切な助けに感謝します。

4

7 に答える 7

5

実際には、コードはタグとタグscriptの間に挿入されます。代わりにこれを使用してください:headbody

var s = document.body.firstChild;
s.parentNode.insertBefore(gtm, s);
于 2013-02-08T09:59:51.813 に答える
3

これに使用できますNode.insertBefore

var body = document.getElementsByTagName("body")[0];
body.insertBefore(gtm, body.firstChild);

これは body タグがなくても機能しfirstChildます。

于 2013-02-08T10:02:06.720 に答える
-1

bodyタグに最初の要素として要素を含め、その直前にスクリプトを追加できますか?使用 yourFirstElementIdfromBodyTag.before(here is your appended code goes)..

例えば

<body>
<your first element> like <input type="hidden" id="hidA" />
//rest code goes here
</body>

今提案された使用法として$('#hidA').before('the script code')。の直後にスクリプトが追加されると確信しています<body>

于 2013-02-08T10:13:20.130 に答える
-1

これを試すことができると思います-appendChild

 document.getElementsByTagName("body")[0].appendChild(gtm);
于 2013-02-08T10:01:02.130 に答える
-1

これを試して:

var script = 'The script content here'; // Add your JS as a string,
var url    = 'path/to/js/file';         // Or link to the file.
var scriptNode = document.createElement('script');       // Create a script Element
scriptnode.setAttribute('type', "text/javascript");      // Set the Element's `type` attribute.
// Either:
scriptNode.appendChild(document.createTextNode(script)); // Add the text to the script Element.
// Or:
scriptNode.setAttribute('src', url);                     // Link to the script
// Place the script Element before the first child of the body.
document.body.insertBefore(scriptNode , document.body.firstChild);

したがって、基本的には、insertBefore

于 2013-02-08T10:02:35.673 に答える
-1

jQuery を使用している場合は、 .prepend()を使用できる場合があります。

(function () {
    var url = "path/to/js/file";
    var gtm = document.createElement('script');
    gtm.type = 'text/javascript';
    gtm.async = true;
    gtm.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + url;
    $('body').prepend(gtm);
})();
于 2013-02-08T10:05:19.307 に答える