Javascript 在 Rails 应用程序中使用外部脚本时出现 null 错误

Javascript null error when using external script in a Rails app

我正在使用来自广告服务提供商的横幅广告,类似于 google adsense。 他们网站上的说明清楚而简单地指出我们需要做的就是将以下代码复制到我们网页的正文中

<!-- Begin Hsoub Ads Ad Place code -->
<script type="text/javascript"><!--
  hsoub_adplace = [my account id];
  hsoub_adplace_size = '728x90';
//--></script>
<script src="http://ads2.hsoub.com/show.js" type="text/javascript"></script>
<!-- End Hsoub Ads Ad Place code -->

我已经复制并粘贴到我的 rails 应用程序中,在视图文件的主体内,但横幅没有显示,我可以看到 javascript 错误(使用浏览器检查源代码)

TypeError: document.getElementById(...) is null

ps:在旧浏览器上会显示横幅,但不会在最新版本的浏览器上显示。

ps2:多次确认hsoub的支持,他们这边没有问题(他们的代码很好,在上千个网站上运行,并且我的帐户处于活动状态,没有任何问题)。这一定是我的代码有问题。我在想 Rails 处理 javascript 的方式... 你能帮我解决这个错误并显示横幅吗?

ps3:我正在使用 rails 6.0.1 和 turbolinks 5.2.0

您可以在 https://tafqit.com/

在线查看 error/source 代码

我猜这是一个脚本定位问题。看起来脚本可能正在寻找尚未呈现的元素,即文档和文档正文尚未准备好。将脚本移动到页面末尾,即在 body 标签之后,看看是否有帮助。否则请添加确切的错误,并可能显示页面的压缩视图和相对于其他元素的脚本。

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <h1>Hello world</h1>
    </body>

    <script type="text/javascript">
        hsoub_adplace = 12345;
        hsoub_adplace_size = '728x90';
    </script>
    <script src="http://ads2.hsoub.com/show.js" type="text/javascript"></script>
</html>

我通过移动脚本

设法让 iframe 加载

脚本(仍然)在 body 标签内。

问题是由 CloudFlare cdn 服务的 Rocket Loader 特性引起的

Rocket Loader improves paint times for pages that include Javascript. Visitors will have a better experience by seeing content load faster and speed is also a factor in some search rankings.

Rocket Loader improves paint times by asynchronously loading your Javascripts, including third party scripts, so that they do not block rendering the content of your pages.

我禁用了它,现在出现了横幅。