簡體   English   中英

當在dom中注入Facebook像素時,jQuery附加到香草JavaScript問題

[英]jQuery append to vanilla javascript issue when injecting a facebook pixel in the dom

我已經編寫了一個腳本,該腳本已在着陸頁的開頭部分顯示。 它的作用是加載一個我存儲在應用程序另一部分中的facebook像素,我可以通過調用端點來訪問它。 這是因為我需要動態更改腳本,而不會干擾登錄頁面本身上的代碼。 這段代碼是用Jquery編寫的,但是現在我需要從我的應用程序中刪除jQuery,所以我嘗試僅使用原始javascript重寫它。

問題在於它可以與jQuery代碼一起正常工作,但是當我嘗試用香草Javascript替換它時,似乎並沒有以正確的方式注入代碼。 DOM中的輸出看起來完全相同,但不會以某種方式觸發像素。

所以我的問題是。 為什么是這樣?

這是我的jQuery腳本的工作示例

<script>
  $.get('https://api.mydomain.com/script', function (data) {
    $('head').append(data);
  });
</script>

這是我的原始Javascript版本

<script>
  var theUrl = 'https://api.mydomain.com/script';
  let xhr = new XMLHttpRequest();
  xhr.open("GET", theUrl);
  xhr.send();
  xhr.onload = function() {
    document.querySelector("head").insertAdjacentHTML("beforeend", xhr.response);
  };
</script>

我認為問題在於insertAdjacentHTML只是一個猜測,但也許它僅適用於HTML(div,圖像等),而不適用於腳本。 希望這種解決方法是可以接受的解決方案:

 (function() { const exampleScript = getScriptContent(` <script> alert("example script loaded"); <\\/script> `), s = document.createElement("script"), t = document.createTextNode(exampleScript); s.appendChild(t); document.getElementsByTagName("head")[0].appendChild(s); function getScriptContent(htmlStr) { const tempDiv = document.createElement("div"); tempDiv.innerHTML = htmlStr; return tempDiv.innerText; } })(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM