我试图在用户滚动时使用 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 中使用条件检查窗口大小,然后使用 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)
关于javascript - 为移动和桌面加载不同的 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67359249/