javascriptjqueryconditional-statementsexternal-script

Loading an external script conditionally not working, no errors


Inside my condition, I have:

var url = "http://ads.eyeonx.ch/adserverscript/custom.min.js";
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
$('.ad').append(script);
console.log('ad loaded');

I received the console message 'ad loaded', but the ad doesn't show up and when I inspect the element, the <script> is not added to the div element with class ad.

No errors showing up with Firebug, anything obvious that I'm missing on why this wouldn't work? I would at least expect the script tag to appear in the element.


Solution

  • The exact problem to this is still unknown as to why the code wasn't showing up when inspecting the element, but I noticed a browser error in the Firefox console (not Firebug console) that complained about the external script using document.write();. It appears that this conflicts with the ability to add it after the page has loaded.

    The solution in my case was to use an iframe. So instead of:

    var url = "http://ads.eyeonx.ch/adserverscript/custom.min.js";
    $("<script>").attr({"type": "text/javascript", "src": url}).appendTo(".ad");
    

    I removed the .ad div and used this code to add an iframe dynamically:

    $("<iframe>").attr({"class": "ad", "src": "/ads/ad.html", "scrolling": "no"}).prependTo('#container');
    

    Which /ads/ad.html just contains the standard <script></script> stuff.