Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 713
Postscripter Avatar asked Jan 25 '23 08:01

Postscripter


2 Answers

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.

like image 162
Postscripter Avatar answered Feb 07 '23 18:02

Postscripter


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, i.e. the document and document body is not ready. Move the scripts to the end of the page i.e. 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.

enter image description here

like image 28
jeeves Avatar answered Feb 07 '23 19:02

jeeves