简体   繁体   English

当在dom中注入Facebook像素时,jQuery附加到香草JavaScript问题

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

I have written a script which I have in the head section on my landing pages. 我已经编写了一个脚本,该脚本已在着陆页的开头部分显示。 What it does is that it loads a facebook pixel which I have stored in another part of my application which I access by calling an endpoint. 它的作用是加载一个我存储在应用程序另一部分中的facebook像素,我可以通过调用端点来访问它。 This because I need to dynamically change the script without interfering with the code on the landing page itself. 这是因为我需要动态更改脚本,而不会干扰登录页面本身上的代码。 This code is written in Jquery but now I need jQuery gone from my application so I've tried to rewrite it using only vanilla javascript. 这段代码是用Jquery编写的,但是现在我需要从我的应用程序中删除jQuery,所以我尝试仅使用原始javascript重写它。

The problem is that it works just fine with the jQuery code, but when I've tried to replace it with vanilla Javascript it does not seem to inject the code in the correct way. 问题在于它可以与jQuery代码一起正常工作,但是当我尝试用香草Javascript替换它时,似乎并没有以正确的方式注入代码。 The output in the DOM looks exactly the same but it does not fire the pixel somehow. DOM中的输出看起来完全相同,但不会以某种方式触发像素。

So my question is. 所以我的问题是。 Why is this? 为什么是这样?

Here is the working example of my jQuery script 这是我的jQuery脚本的工作示例

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

Here is my vanilla Javascript version 这是我的原始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>

I think the issue is with insertAdjacentHTML - just a guess, but maybe it only works for HTML (divs, images, etc.) rather than scripts. 我认为问题在于insertAdjacentHTML只是一个猜测,但也许它仅适用于HTML(div,图像等),而不适用于脚本。 Hopefully this workaround is an acceptable solution: 希望这种解决方法是可以接受的解决方案:

 (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