JavaScript 加载顺序导致问题

2024-01-23

我在标头中有一个 JS 文件(这是用于 Google DFP 的),在</body>

我发现如果头 JS 文件没有在底部文件之前加载,我会在 Chrome 控制台中收到此错误:

 Uncaught TypeError: Object #<Object> has no method 'defineSlot' 

DefineSlot 在第一个脚本中定义。此问题仅在大约每 10 次页面刷新时发生,因此大多数情况下都没有问题。

我想要关于如何处理这个问题的建议。下面是 2 个脚本:

标头脚本:

<script type='text/javascript'>
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
(function() {
    var gads = document.createElement('script');
    gads.async = true;
    gads.type = 'text/javascript';
    var useSSL = 'https:' == document.location.protocol;
    gads.src = (useSSL ? 'https:' : 'http:') + 
    '//www.googletagservices.com/tag/js/gpt.js';
    var node = document.getElementsByTagName('script')[0];
    node.parentNode.insertBefore(gads, node);
})();
</script>

<script type='text/javascript'>
googletag.cmd.push(function() {
    googletag.pubads().enableAsyncRendering();
    slot1 = googletag.defineSlot('/21848415/GoneGlobal_Square', [250, 250], 'doubleClickSquareIndex-250-250').addService(googletag.pubads());
    slot2 = googletag.defineSlot('/21848415/GoneGlobal_Skyscraper', [160, 600], 'doubleClickSkyscraperIndex-160-600').addService(googletag.pubads());
    slot3 = googletag.defineSlot('/21848415/GoneGlobal_Leaderboard', [728, 90], 'doubleClickLeaderboardIndex-728-90').addService(googletag.pubads());
    slot4 = googletag.defineSlot('/21848415/GoneGlobal_Leaderboard', [728, 90], 'doubleClickLeaderboardHeaderInternal-728-90').addService(googletag.pubads());
    slot5 = googletag.defineSlot('/21848415/GoneGlobal_SmallSquare', [200, 200], 'doubleClickSmallSquareHeaderExternal-200-200').addService(googletag.pubads());
    googletag.enableServices();
});
</script>

下面是第二个脚本 - 这只是它的一部分(它很长):

$(function() {
    ///////////////////////// Double Click AD Variables
    var slot1 = googletag.defineSlot('/21848415/GoneGlobal_Square', [250, 250], 'doubleClickSquareIndex-250-250');
    var slot2 = googletag.defineSlot('/21848415/GoneGlobal_Skyscraper', [160, 600], 'doubleClickSkyscraperIndex-160-600');
    var slot3 = googletag.defineSlot('/21848415/GoneGlobal_Leaderboard', [728, 90], 'doubleClickLeaderboardIndex-728-90');
    var slot4 = googletag.defineSlot('/21848415/GoneGlobal_Leaderboard', [728, 90], 'doubleClickLeaderboardHeaderInternal-728-90');
    var slot5 = googletag.defineSlot('/21848415/GoneGlobal_SmallSquare', [200, 200], 'doubleClickSmallSquareHeaderExternal-200-200');
)};

有没有办法阻止脚本运行另一个加载的方法/函数?

我可以创建某种依赖关系吗?

如何确保顶部JS先于底部加载?


这里的其他解决方案可能有效,但真正的问题在于您使用 DFP 广告管理系统的方式。

DFP 广告管理系统是异步加载的,因此在执行导致错误的脚本时,您的页面上将不存在 DefineSlot 方法。

您的所有 DFP 广告管理系统代码均应包含在googletag.cmd.push包装器将存储命令,直到加载 DFP,然后以正确的顺序执行它们。

像这样简单地包装任何 DFP 代码,应该可以修复您的错误:

googletag.cmd.push(function() {
    // Double Click AD Variables

});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JavaScript 加载顺序导致问题 的相关文章