I'm having a problem with my script because of the AdSense script... when the AdSense script fails to load, my script runs well, but if AdSense loads, My script doesn't load. And I know my script runs AFTER the AdSense script.
So I'm thinking, if my script runs before the AdSense script runs (because is a script to change a pre tag to a table, therefore it only changes the layout), everything will load, instead of just loading the AdSense...
My javascript is:
window.onload = function(){
var preElements = document.getElementsByTagName('pre');
var codeLine = new Array();
var newContent
for(var i = 0; i < preElements.length; ++ i)
{
var element = preElements[i];
newContent='<div align="center"><table width="75%" border="1" cellpadding="0" cellspacing="0" >'
codeLine = element.innerHTML.split('\n');
for(var j=0 ; j < codeLine.length ; j++){
newContent = newContent + '<tr><td width="30" class="codeNumber" >' + j.toString() + ' </td><td class="codeTab"> ' + codeLine[j] + '</td></tr>';
}
newContent = newContent + '</table></div>';
element.innerHTML = newContent;
}
}
It is loaded on the Head section and the AdSense is loaded inside a cell and I only have one adspace.
I can't give an ID to cell because the AdSense isn't the only thing on the cell... And another thing.. The place where the AdSense is being called is completely different where i have the pre tag's
SOLVED: First I really didn't know much about this, and after a little research I've found the problem.
1º The AdSense was having a connection problem, and because of that all the scripts that runs after it, will not load
2º It doesn't matter where you have the script if you have "window.onload" in it... I thought that function worked when the window is loading but actualy, it will function after the window fully loads, and this is why it was creating a conflict with the AdSense.
You guys helped me see this things faster!
Generally most people put Ad and Analytics code includes right before the closing </body> tag.
You should try to avoid race conditions with your code, from loading to execution it should be event driven and modular. If Adsense needs to go in a container that is being set by another script, it would make sense to have that other script load Adsense when it's finished updating your DOM, as a callback. Something like this:
function loadAdsense(elementId) {
var js = document.createElement('script');
js.src = 'http://pagead2.googlesyndication.com/pagead/show_ads.js';
window.google_ad_client = 'ca-pub-xxxxxxxxxxxx';
window.google_ad_slot = '1234567890';
window.google_ad_width = 336;
window.google_ad_height = 280;
document.getElementById(elementId).appendChild(script);
}
function preToTable() {
// set PRE to TABLE - id = myNewTable
// then load Adsense
loadAdsense('myNewTable');
}
You should place your javascript in the head tag, and the AdSense code at the end of your content. Another solution is to use a javascript event to print the AdSense script when your first script is done.
SOLVED: First I really didn't know much about this, and after a little research I've found the problem. 1º The AdSense was having a connection problem, and because of that all the scripts that runs after it, will not load 2º It doesn't matter where you have the script if you have "window.onload" in it... I thought that function worked when the window is loading but actualy, it will function after the window fully loads, and this is why it was creating a conflict with the AdSense.
Related
I have a site with many pages and I want to start with Google Ads on it... so I want to insert ads to all the pages, but I want to find a good way... I don't want to add the code manually in all the files... so I tried to build a function to add the google's adsense block after some paragraphs using javascript:
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXX" crossorigin="anonymous"></script>
var display_block = '<ins class="adsbygoogle"' +
'style="display:block"' +
'data-ad-client="ca-pub-XXXXX"' +
'data-ad-slot="xxxxxxxxxx"' +
'data-ad-format="auto"' +
'data-full-width-responsive="true"></ins>' +
'<script>' +
'(adsbygoogle = window.adsbygoogle || []).push({});' +
'</script>';
var afterparagraph1 = document.getElementById('article').getElementsByTagName('p')[0]
afterparagraph1.insertAdjacentHTML('afterend', display_block );
var afterparagraph3 = document.getElementById('article').getElementsByTagName('p')[3]
afterparagraph3.insertAdjacentHTML('afterend', display_block );
Well the code is added (I can see when inspect with console) but the ads doesn´t appear... but if I insert the code manually inside each html file it appears... :(
Do you know what I am doing wrong?
Thanks for your time :)
I have issues firing this link (that triggers a script from Chargebee) when is added dynamically via JavaScript. When it's added directly in html it works normally.
The entire generated link is appearing correctly (populated with the variants) in browser when inspected just it doesn't fire.
Here are the pieces I have related to this:
The JavaScript part:
var checkout = document.getElementById("checkout");
var link = '<a href="javascript:void(0)" data-cb-type="checkout"' + data-cb-1 + data-cb-2 + data-cb-3'>Order</a>';
checkout.innerHTML = link;
A simple div:
<div id="checkout"></div>
The script from chargebee:
<script src="https://js.chargebee.com/v2/chargebee.js" data-cb-site="site-name"></script>
Once you've loaded chargebee.js script it starts to look for a tag a with specific data-cb attributes. The script does it one time only. If the tag a did not exist in the DOM then, the script does nothing. When you add the tag a later that makes no effect at all, because a "discovery phase" is over.
If you want to have more control over chargebee initialisation process, you should go for "Checkout via API" option provided by the developers.
P.S. There are two hacky solutions:
You may load Chargebee script after adding tag a to the DOM.
function loadChargebee() {
var script = document.createElement("script");
script.src = "https://js.chargebee.com/v2/chargebee.js";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
}
var checkout = document.getElementById("checkout");
var link = '<a href="javascript:void(0)" data-cb-type="checkout"' + data-cb-1 + data-cb-2 + data-cb-3'>Order</a>';
checkout.innerHTML = link;
loadChargebee(); // <=== add Chargebee.js
Leave the tag a in the DOM, load the script as usual but modify data attributes as needed after page load:
<a id="beecheckout" href="javascript:void(0)" data-cb-type="checkout" data-cb-1="" data-cb-2="" data-cb-3="">Order</a>
document.getElementById('beecheckout').setAttribute('data-cb-1','new data value');
I am using CSS-Tricks dynamic page script found here.
http://css-tricks.com/dynamic-page-replacing-content/
$(function() {
var newHash = "",
$mainContent = $("#main-content"),
$pageWrap = $("#page-wrap"),
baseHeight = 0,
$el;
$pageWrap.height($pageWrap.height());
baseHeight = $pageWrap.height() - $mainContent.height();
$("nav").delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function(){
newHash = window.location.hash.substring(1);
if (newHash) {
$mainContent
.find("#guts")
.fadeOut(200, function() {
$mainContent.hide().load(newHash + " #guts", function() {
$mainContent.fadeIn(200, function() {
/*
$pageWrap.animate({
height: baseHeight + $mainContent.height() + "px"
});
*/
});
$("nav a").removeClass("current");
$("nav a[href="+newHash+"]").addClass("current");
});
});
};
});
$(window).trigger('hashchange');
});
Body
<body onload="onLoad()">
I am using a number generating script (below) on one of my pages, but I am having trouble getting it to only show on one, single page. When placed in the head of the document or my includes/scripts.php that is loaded on every page, it shows on every page. When only included on the page I want, it does not work.
<script>
function counter() {
var num = 0;
for (num = 0; num < 500; num++) {
document.write(num + ' ');
}
}
counter();
</script>
I have tried a few different things but can't seem to get it to only appear on a single page. Is there any way around this without ditching the CSS-Tricks Dynamic Page?
What if you insert your code into dynamicpage.js like this?
$(window).bind('hashchange', function(){
newHash = window.location.hash.substring(1);
if(newHash === 'somePage') { // the page you want to implement the effect
// your code
}
/*
....
*/
});
You might try adding a class to your <body> tag (or other near-to-top level wrapper if you're just dynamically loading to the HTML attribute of your body tag in the first place) that lets the script distinguish between pages that ought to use the function and those that don't, something like:
$(document).ready( function() {
$(`body.usesCounter`).on(eventToBeCounted, counterFuncAsCallback);
}
But the fact that it's not working when only loaded on a single page does suggest you've got something else going on. Can you give us the header for the single page, the script block (and where it is on the page), and some sense of how/when it's called?
Are you loading the single page dynamically? If you are, the script tags won't be accessible unless you reload the DOM somehow or else do some funky binding via jQuery's $.on() or something similar that listens for changes to the DOM.
UPDATE
Looking at the tutorial you are trying to emulate, the general problem you're facing is that the JS on that page you're loading isn't going to be registered with the DOM. I've had to write code that can read dynamically lodaded JS like this, and if you want to do it both effectively and securely, it's quite a lot of effort. The point of JS-based page loading is to be fetching "view-like" content; assets, html, etc.. In a single-page environment, any required logic should—generally—exist on that page.
I highly recommend you include the code in your initial page, and then conditionally call it when the appropriate page arrives. There are lots and lots of ways to do that, basically find some distinguishing feature of the page(s) where your counter should be run, and, after having loaded the page, look for said features and, if found, allow your code to run. You might have something as simple as a variable, isCounterPage set, by default, to false. Then, after a dynamic page load occurs, if the inspection fires and this var remains false, don't execute code associated with the counter. Otherwise, let it do its thing.
Say I have a string named html that has this in it:
<script>
document.write("Some random stuff here");
</script>
<script src="someremotejsfile"></script>
I want to display this within an iframe window dynamically.
My original solution was to do:
document.open();
document.write(html);
document.close();
But this causes problems in firefox where the spinner keeps spinning as if its loading forever even though the content has already loaded. My next attempt was to:
document.body.innerHTML = html;
This adds the scripts to the body, but that doesn't actually execute them. So lastly I tried:
div = document.createElement("div");
div.innerHTML = html;
document.body.appendChild(div);
But this also doesn't seem to execute the scripts inside the html string.
So my question is, given a string of html, how do I dynamically add it to the page? For instance, it can be an ad tag that has any number of scripts and other html elements in it. I have no control over what that html string has in it. It's a black box to me. I just have to be able to take that long string of html and load it into the window (an iframe in this case).
document.write works:
<iframe id="ifr"></iframe>
<script type="text/javascript">
var scr = decodeURIComponent("%3Ch1%3EHello%20World%3C%2Fh1%3E%3Cscript%3Ealert(%27Some%20random%20stuff%20here%27)%3B%3C%2Fscript%3E");
document.getElementById("ifr").contentWindow.document.write(scr);
document.getElementById("ifr").contentWindow.document.close();
</script>
(Never mind encoded URI string, just needed it to be able to assign code <h1>Hello World</h1><script>alert('Some random stuff here');</script> to a string variable inside of script tags
If you're using jQuery you can use .html to load, and it will fire your script
$(document.body).html( $(document.body).html() + htmlToAdd );
If you're not using jQuery, you can eval manually your script..
function appendHTMLtoBody(html){
var body = document.body;
var scriptsLoaded = [].slice.apply(body.getElementsByTagName("script"),[0]);
for(var i = 0; i < scriptsLoaded.length; i++){
scriptsLoaded[i].setAttribute("data-loaded","true");
}
body.innerHTML += html;
var allScripts = body.getElementsByTagName("script");
for(var i = 0; i < allScripts.length; i++){
if( allScripts[i].getAttribute("data-loaded") !== "true" ){
var script = allScripts[i].innerHTML;
eval(script);
}
}
}
i think will solve your problem.
I have an issue where the JavaScript source file is loading in popup for IE6, Chrome, Firefox, Safari and Opera. But the same source file is not loading up in IE8.
As a result of this the HTML is not being replaced in the Popup and I am getting an error in IE8 popup saying tinyMCE is not defined
I have referred to Formatting this JavaScript Line and solved issue on all browsers except IE8.
The JavaScript function is as follows:
function openSupportPage() {
var features="width=700,height=400,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes";
var winId=window.open('','',features);
winId.document.open();
winId.document.write('<html><head><title>' + document.title + '</title><link rel="stylesheet" href="../css/default.css" type="text/css">\n');
var winDoc = winId.document;
var sEl = winDoc.createElement("script");
sEl.src = "../js/tiny_mce/tiny_mce.js";/*TinyMCE source file*/
sEl.type="text/javascript";
winDoc.getElementsByTagName("head")[0].appendChild(sEl);
winId.document.write('<script type="text/javascript">\n');
winId.document.write('function inittextarea() {\n');
winId.document.write('tinyMCE.init({ \n');
winId.document.write('elements : "content",\n');
winId.document.write('theme : "advanced",\n');
winId.document.write('readonly : true,\n');
winId.document.write('mode : "exact",\n');
winId.document.write('theme : "advanced",\n');
winId.document.write('readonly : true,\n');
winId.document.write('setup : function(ed) {\n');
winId.document.write('ed.onInit.add(function() {\n');
winId.document.write('tinyMCE.activeEditor.execCommand("mceToggleVisualAid");\n');
winId.document.write('});\n');
winId.document.write('}\n');
winId.document.write('});}</script>\n');
window.setTimeout(function () {/*using setTimeout to wait for the JS source file to load*/
winId.document.write('</head><body onload="inittextarea()">\n');
winId.document.write(' \n');
var hiddenFrameHTML = document.getElementById("HiddenFrame").innerHTML;
hiddenFrameHTML = hiddenFrameHTML.replace(/&/gi, "&");
hiddenFrameHTML = hiddenFrameHTML.replace(/</gi, "<");
hiddenFrameHTML = hiddenFrameHTML.replace(/>/gi, ">");
winId.document.write(hiddenFrameHTML);
winId.document.write('<textarea id="content" rows="10" style="width:100%">\n');
winId.document.write(document.getElementById(top.document.forms[0].id + ":supportStuff").innerHTML);
winId.document.write('</textArea>\n');
var hiddenFrameHTML2 = document.getElementById("HiddenFrame2").innerHTML;
hiddenFrameHTML2 = hiddenFrameHTML2.replace(/&/gi, "&");
hiddenFrameHTML2 = hiddenFrameHTML2.replace(/</gi, "<");
hiddenFrameHTML2 = hiddenFrameHTML2.replace(/>/gi, ">");
winId.document.write(hiddenFrameHTML2);
winId.document.write('</body></html>\n');
winId.document.close();
}, 300);
}
Additional Information:
Screen shot of the page
Rendered HTML
Original JSPF
please help me with this one.
Why are you using actual DOM functions to add the <script> tag that includes tinymce.js but everything else is using document.write?
I think that's also where your problem lies, as <head> is within <html>, which is not yet closed where you want to append said <script> tag.
Otherwise, you could use the existing <script> tag in the popup to add the code that includes the required external javascript file. If that makes any sense.
So, basically I'm saying, try it the same way as everything else is in your script, using document.write.
(quick addition) I'm not saying this is the 'best' way to do this, I would recommend creating an actual page instead of dynamically creating one in the popup. But in this scenario, I think what I wrote earlier might solve the problem you are having.