简体   繁体   中英

Javascript null error when using external script in a Rails app

I am using a banner ad from an ad service provider, similar to google adsense. Instruction from their site state clearly and simply that all we need to do is to copy the below code to the body of our webpage

<!-- 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 -->

I have copied and pasted into my rails app, inside a body of a view file but the banner is not getting displayed and I can see javascript error (with browser inspect source)

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

ps : On old browsers the banner is getting displayed but never on recent versions of browsers.

ps2 : The support of hsoub confirmed multiple times, there is no problem from their side (their code is fine and working on thousands of websites, and my account is active with no issues). And it must be a problem from my code.. I am thinking the way Rails handles javascript... Can you please help me solve this error and get the banner displayed.

ps3 : I am using rails 6.0.1 and turbolinks 5.2.0

you can check the error/source code online at https://tafqit.com/

The problem is caused by Rocket Loader feature of CloudFlare cdn service

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.

I disabled it and banner is appearing now.

I am going to guess that this is a script positioning issue. It looks like the script is possibly looking for elements that are not rendered yet, ie the document and document body is not ready. Move the scripts to the end of the page ie after the body tags and see if that helps. Otherwise please add the exact error and perhaps show a condensed view of your page and the scripts relative to the other elements.

<!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>

I managed to get the iframe to load by moving the scripts

Scripts are (still) inside the body tags.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM