为移动和桌面加载不同的 JS

Load different JS for Mobile and Desktop

我正在尝试使用 JS 在用户滚动时加载广告代码。 代码是:

<script type='text/javascript'>//<![CDATA[ var la=!1;window.addEventListener("scroll",function(){(0!=document.documentElement.scrollTop&&!1===la||0!=document.body.scrollTop&&!1===la)&&(!function(){var e=document.createElement("script");e.type="text/javascript",e.async=!0,e.src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(e,a)}(),la=!0)},!0);//]]></script>

现在,我想要上面的 JS 应该只为移动设备加载, 对于桌面,它应该加载:

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

感谢你的付出

在你的javascript中使用条件检查window大小,然后使用javascript设置脚本标签,根据条件设置相关属性和内容,然后附加你的头.

let mediaBreakpointSize = 600; /* Change this size and test outcome */

let scriptTag = '';

if (document.documentElement.clientWidth < mediaBreakpointSize) {

  scriptTag = document.createElement("script");

  let content = '//<![CDATA[ var la=!1;window.addEventListener("scroll",function(){(0!=document.documentElement.scrollTop&&!1===la||0!=document.body.scrollTop&&!1===la)&&(!function(){var e=document.createElement("script");e.type="text/javascript",e.async=!0,e.src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(e,a)}(),la=!0)},!0);//]]';
  
  scriptTag.setAttribute('type', 'text/javascript');
  
  scriptTag.defer = true;
  
  scriptTag.textContent = content;
  
  document.head.appendChild(scriptTag);
  
} else {

  scriptTag = document.createElement("script");

  scriptTag.async = true;

  scriptTag.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";

  document.head.appendChild(scriptTag);
}

console.log(scriptTag)