Using jQuery to insert Javascript code into a DIV - javascript

Okay, so I'm working on a responsive site and I'm trying to handle Adsense in the best way possible that doesn't get me banned! What I'd like to do is use jQuery to add in my Adsense code only if the browser width is less than 533px. This way, I can display a smaller ad that will fit the window properly and not break the layout. I'm having some trouble getting the Adsense javascript added though. This works:
(function($){
//detect the width on page load
$(document).ready(function(){
var current_width = $(window).width();
//do something with the width value here!
if(current_width < 533){
$('.ads').prepend("THIS IS WHERE I WANT THE ADSENSE CODE TO GO");
}
});
But when I include my Adsense code to replace THIS IS WHERE I WANT THE ADSENSE TO GO, it doesn't. This is the Adsense code:
<script type="text/javascript"><!--
google_ad_client = "ca-pub-1234567890";
/* Test Ad */
google_ad_slot = "1234567890";
google_ad_width = 250;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
I've also tried to include the Adsense javascript code in a .html file and use jQuery.get and jQuery.getScript for a .html and .js file. I just can't get it to work.
I could do it with a simple PHP header detect, but I want the ads to display based on width, not device type.
Anybody know how this can be done?
(Reposted as no replies to previous question)

I'm not sure if this will work or not, but it's worth a shot:
/* these should be global */
google_ad_client = "ca-pub-1234567890";
/* Test Ad */
google_ad_slot = "1234567890";
google_ad_width = 250;
google_ad_height = 250;
$(function(){
//detect the width on page load
var current_width = $(window).width();
//do something with the width value here!
if(current_width < 533){
$.getScript('http://pagead2.googlesyndication.com/pagead/show_ads.js');
}
});

The problem you're facing is that Google doesn't really support AdSense ajax. The normal way of including adsense code uses the URL of the page where it lives in order to render the right content.
Now, suppose you could reduce the adsense code to a particular URL. You could do something like this:
// note, this url is just a suggestion, not something that will likely work
var url = 'http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-1234567890&ad_slot=1234567890&ad_width=250&ad_height=250';
var adsContainer = $('.ads'); // though, if there's only one, use id, not class
$.ajax({
type:'GET',
url:url,
async:true,
success:function(html) {
adsContainer.html(html);
return false;
},
error: function(html) {
adsContainer.html('SOME DEFAULT AD MESSAGE');
return false;
}
});
But I think this is almost assuredly the kind of thing that will get you in trouble with Google.
Google used to have an adsense ajax program:
https://developers.google.com/adsense-for-ajax/
But it is now "unavailable". The reason you can't put your code in an external .html or .php file and ajax on your own server is that the javascript doesn't get executed by an engine on the client side by the ajax call. You are injecting raw javascript into a page that has already been interpreted by the javascript engine.
Could you use node.js or some kind of server side javascript parser to serve your .html file? Maybe, but that's a lot to solve this problem.
My advice is this: include multiple, smaller ads that will look good if stacked on a big page, or tiled if crammed together on a small page.

Have you tried lading the external .js like this?
var script = document.createElement('script');
script.src = 'http://pagead2.googlesyndication.com/pagead/show_ads.js';
script.type = 'text/javascript';
var head = document.getElementsByTagName("head")[0];
head.appendChild(script);

Related

Trouble loading js

I'm sorry in advance if this is simple or if it just can't be done. Basically, I am trying to load an age verification js on my site, but I am trying to chose between different pages depending on the legal drinking age in different countries.
If I load the script simply, it works fine:
<script type="text/javascript" src="https://av.ageverify.co/jsfr/singlemalt.18.js"></script>
However, if I trying to do any sort of modification to this script, it won't load at all. For example, if I try to set the src to a variable (that I would call in a different script, it fails to load).
<script>
url = "https://av.ageverify.co/jsfr/singlemalt.18.js";
</script>
<script type="text/javascript" src=url></script>
Any ideas would be greatly appreciated!
EDITED:
Additional info:
I tried to use getScript as people have suggested but also had issues with it:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
$.getScript("https://av.ageverify.co/jsfr/singlemalt.18.js");
</script>
or this method:
function loadJs() {
var url = "https://av.ageverify.co/jsfr/singlemalt.18.js";
var script = document.createElement("script");
script.src = url;
document.head.appendChild(script);
}
This last one seems to work with other simple scripts, but maybe this particular script is looking for some sort of browser condition? Any suggestions on how to figure that out or what to look for? There should be an age verification page that pops up, asking your age.
HTML tags do not understand variables. You need to use a URL for the src attribute. HTML has no idea what your JavaScript variables are.
If you want to load the .js file this way, you need to use JavaScript. What you can do is create a new <script> tag then append it to the page.
var url = "https://av.ageverify.co/jsfr/singlemalt.18.js";
var script = document.createElement("script");
script.src = url;
document.head.appendChild(script);
If you are using jQuery, this is basically what $.getScript does.
var url = "https://av.ageverify.co/jsfr/singlemalt.18.js";
$.getScript(url);

php if - screen width - load js

I'm new to php. I have a doubt, don't know if this can be done, or if it should be done in another way or what.
I want to load a JS only if the screen size is higher than x size.
I wrote this but the JS is not being loaded (in fact I want to load a couple of JS):
<script language="javascript">
if (screen.width > 549) {
<script src='js/jquery-1.8.1.min.js' type='text/javascript'></script>
}
best regards!
php cannot detect a clients screen width/height, that all would have to be done client side.
function addScript(src){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = src;
document.head.appendChild(script);
}
if(screen.width > 549){
addScript("js/jquery-1.8.1.min.js");
addScript("js/someOtherScript.js");
}
It's cleaner to detect the screen width in JavaScript. Also remember the screensize can change in a session. For example when a user resizes his screen.
Use this in your JavaScript file:
var width = document.body.clientWidth;
if(width > 549) {
} else if(width < 300) {
} else {
}
You cannot determine a clients' browser window size before a client has received a page with PHP.
Technically you could load a page, get javascript to send back the window size and then store it in the session for that user, but I don't really see the point. You're better off either always including the javascript file, or using a javascript library to conditionally add other scripts to the DOM.

Site content shifts vertically on certain pages

I'm in the process of building a new website for my wife's business, using Squarespace. Don't tell her, since it's one of her Christmas presents. :)
However, I'm experiencing a weird issue. About half of the pages on the site include content from a third-party widget called Healcode. Those pages have a strange jerkiness to them on pageload, where the logo and navbar move around -- ultimately winding up in the right spot, but looking bad while doing so. Pages that don't have a third-party widget don't have this jerkiness.
Example of page that jerks: https://coconditioning.squarespace.com/yoga-classes/
Example of page that doesn't jerk: https://coconditioning.squarespace.com/private-coaching/
The Healcode widget is javascript code that looks like this:
<script type="text/javascript">
healcode_widget_id = "ay12237c4nc";
healcode_widget_name = "schedules";
healcode_widget_type = "mb";
document.write(unescape("%3Cscript src='https://www.healcode.com/javascripts/hc_widget.js' type='text/javascript'%3E%3C/script%3E"));
// Healcode Schedule Widget for Conscious Conditioning L.L.C. : Weekly Schedule New
</script>
<noscript>Please enable Javascript in order to get HealCode functionality</noscript>
Any help would be MUCH appreciated. Thank you in advance!
You could hide the page until the body loads:
<body style = 'display: none'; />
And in your javascript, adding window.onload():
healcode_widget_id = "ay12237c4nc";
healcode_widget_name = "schedules";
healcode_widget_type = "mb";
document.write( unescape("%3Cscript src='https://www.healcode.com/javascripts/hc_widget.js' type='text/javascript'%3E%3C/script%3E"));
// Healcode Schedule Widget for Conscious Conditioning L.L.C. : Weekly Schedule New
window.onload = function()
{
document.body.style.display = 'block';
};
Also, is document.write() the best solution for you?
Don't try to use document.write if possible as with document.write JS parser doesn't know where to put it. at best, the browser will ignore it. at worst, it could write over the top of your current document. Use appendChild
function loadHealCodeScript () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://www.healcode.com/javascripts/hc_widget.js'
document.body.appendChild(script);
}
window.onload = loadHealCodeScript; // load healcode after page has been loaded
The jittering effect is happening because the healcode is loading its script before the page has completely loaded. If possible place all you javascripts after the body tag rather than head
As suggested by google also https://developers.google.com/maps/documentation/javascript/tutorial?hl=en#asynch

Inserting and executing conditional javascript

Working on a Mobile First design and want to conditional load and execute some JavaScript based on the browser width.
UPDATE: (more info on what I'm doing)
I'm looking to conditionally load different size Google DFP ads depending on the width of the browser window. So a desktop/iPad might see a 720 pixel wide ad, a wide mobile might see a 480px ad and a basic mobile might see a 320px ad.
Google DFP has an asynchronous method which has the main code in the head. Ad calls are then made via a combination of a div with a numbered id and a function call that has the same number.
So in what I'm trying to accomplish, I need to insert both a numbered div and a specific numbered function call into the div where I want the specific ad call to appear.
Looked around for conditional examples and this worked in my test:
<div id="ad"></div>
<script type="text/javascript">
var ad = document.getElementById("ad");
if (document.documentElement.clientWidth > 640) {
ad.innerHTML = "big";
}
if (document.documentElement.clientWidth < 640) {
ad.innerHTML = "small";
}
</script>
Obviously just a test of the width checking and not the ad call.
If I understand correctly, innerHTML won't work if I need to dynamically load and execute some JavaScript.
Basically, when I test for the size I have to enter an ad call like this into the #ad div:
<div id='div-gpt-ad-xxxxxxxxxxx-2'
style='width:728px;height:90px;margin:auto'><script type='text/javascript'>
googletag.cmd.push(function() { googletag.display('div-gpt-ad-xxxxxxxxxxx-2'); });
</script></div>
Notice the "-2" in both the div and function. That will be different for the different ad sizes.
Completely new to DOM manipulation so any help is greatly appreciated.
You are correct that script elements inserted using the innerHTML property aren't executed.
A simple solution is to collect the script elements that were inserted and replace them with new elements where the code will be executed, e.g.
function insertAndExecute(id, markup) {
var sOld, sNew, scripts;
var s;
var el = document.getElementById(id);
if (el) {
s = document.createElement('script');
el.innerHTML = markup;
scripts = el.getElementsByTagName('script');
for (var i=0, iLen=scripts.length; i<iLen; i++) {
sOld = scripts[i];
sNew = s.cloneNode(true);
sNew.type = sOld.type;
if (sOld.src) {
sNew.src = sOld.src;
} else {
sNew.text = sOld.text;
}
sOld.parentNode.replaceChild(sNew, sOld);
}
}
}
It is much better if the scripts have a src attribtue and load an external file.
As jfriend00 says, if you can determine the markup to be inserted during page load, document.write is a viable alternative as it will cause included scripts to be executed. But you can't use it after the page has finished loading.
Edit
As for getting the width of the window:
var width = window.innerWidth || document.body.clientWidth;
should do. Note that in IE, clientWidth is 20px less than the window width because it allows for a vertical scroll bar. But that shouldn't matter here.
Also, clientWidth shouldn't be measured until the document has finished loading so the layout is complete (use onload or something later), and make sure documents have a DOCTYPE so that IE is in standards mode (or "almost standards mode" or whatever).
You might also be interested in How to Measure the Viewport.
If you're new to DOM manipulation, then stop right now and find a JavaScript library that you like. The DOM is by far the most frustrating part of using JavaScript in the browser, so don't ruin your first experience with the language by not using a library that helps you with it. Two good options are YUI and jQuery. This is important because you can't get the width of the screen reliably with document.documentElement.clientWidth. Different browsers use different properties for it.
Regarding your question, in this case it's just a matter of running the code in your script after inserting the content into the ad container.
<div id="ad"></div>
<script>
document.getElementById('ad').innerHTML = '<div id="div-gpt-ad-xxxxxxxxxxx-2" style="width:728px;height:90px;margin:auto"></div>';
if (screenWidth > 640) {
googletag.cmd.push(function() {
googletag.display('div-gpt-ad-xxxxxxxxxxx-2');
});
} else {
// do something else
}
</script>

How can we keep OpenX from blocking page load?

We're using OpenX to serve ads on a number of sites. If the OpenX server has problems, however, it blocks page loads on these sites. I'd rather have the sites fail gracefully, i.e. load the pages without the ads and fill them in when they become available.
We're using OpenX's single page call, and we're giving divs explicit size in CSS so they can be laid out without their contents, but still loading the script blocks page load. Are there other best practices for speeding up pages with OpenX?
We load our ads in iframes to avoid the problem you're having. We size div and the iframe the same, with the iframe pointing to a page which just contains the ad snippet (you can pass the zone and other required options as parameters to that page).
cheers
Lee
We lazy-load OpenX's code. Instead of putting the single-page call at the top of the page, we put it at the bottom. After the page has loaded, the call will get the banner data and a custom code will add the correct banners in the correct zones.
The code below requires a proper DOM. If you have jQuery, DOMAssistant, FlowJS, etc, the DOM should be fixed for you.
This code will work with normal banners with images, flash, or HTML content. It may not work in some cases like when using banners from external providers (adform, etc). For that you may need to hack the code a bit.
How to use it?
add your SinglePageCall code towards the end of your HTML code
add this code under the SPC code.
after half a second or so, your OpenX code should be ready, and the code below will put the banners within the specified DIVs.
Oh, yeah, you need to add to your HTML code some DIVs as place holders for your banners. By default I have these banners set with CSS class "hidden" which totally hides the DIVs (with visibility, display, and height). Then, after the banner in a given DIV is successfully loaded, we remove the hidden class and the DIV (and the banner within) become visible.
Use at your own risk! :) Hope it helps
(function(){
if (!document || !document.getElementById || !document.addEventListener || !document.removeClass) {
return; // No proper DOM; give up.
}
var openx_timeout = 1, // limit the time we wait for openx
oZones = new Object(), // list of [div_id] => zoneID
displayBannerAds; // function.
// oZones.<divID> = <zoneID>
// eg: oZones.banner_below_job2 = 100;
// (generated on the server side with PHP)
oZones.banner_top = 23;
oZones.banner_bottom = 34;
displayBannerAds = function(){
if( typeof(OA_output)!='undefined' && OA_output.constructor == Array ){
// OpenX SinglePageCall ready!
if (OA_output.length>0) {
for (var zone_div_id in oZones){
zoneid = oZones[zone_div_id];
if(typeof(OA_output[zoneid])!='undefined' && OA_output[zoneid]!='') {
var flashCode,
oDIV = document.getElementById( zone_div_id );
if (oDIV) {
// if it's a flash banner..
if(OA_output[zoneid].indexOf("ox_swf.write")!=-1)
{
// extract javascript code
var pre_code_wrap = "<script type='text/javascript'><!--// <![CDATA[",
post_code_wrap = "// ]]> -->";
flashCode = OA_output[zoneid].substr(OA_output[zoneid].indexOf(pre_code_wrap)+pre_code_wrap.length);
flashCode = flashCode.substr(0, flashCode.indexOf(post_code_wrap));
// replace destination for the SWFObject
flashCode = flashCode.replace(/ox\_swf\.write\(\'(.*)'\)/, "ox_swf.write('"+ oDIV.id +"')");
// insert SWFObject
if( flashCode.indexOf("ox_swf.write")!=-1 ){
eval(flashCode);
oDIV.removeClass('hidden');
}// else: the code was not as expected; don't show it
}else{
// normal image banner; just set the contents of the DIV
oDIV.innerHTML = OA_output[zoneid];
oDIV.removeClass('hidden');
}
}
}
} // end of loop
}//else: no banners on this page
}else{
// not ready, let's wait a bit
if (openx_timeout>80) {
return; // we waited too long; abort
};
setTimeout( displayBannerAds, 10*openx_timeout );
openx_timeout+=4;
}
};
displayBannerAds();
})();
OpenX has some documentation on how to make their tags load asynchronously:
http://docs.openx.com/ad_server/adtagguide_synchjs_implementing_async.html
I've tested it, and it works well in current Chrome/Firefox.
It takes some manual tweaking of their ad code. Their example of how the ad tags should end up:
<html>
<head></head>
<body>
Some content here.
Ad goes here.
<!-- Preserve space while the rest of the page loads. -->
<div id="placeholderId" style="width:728px;height:90px">
<!-- Fallback mechanism to use if unable to load the script tag. -->
<noscript>
<iframe id="4cb4e94bd5bb6" name="4cb4e94bd5bb6"
src="http://d.example.com/w/1.0/afr?auid=8&target=
_blank&cb=INSERT_RANDOM_NUMBER_HERE"
frameborder="0" scrolling="no" width="728"
height="90">
<a href="http://d.example.com/w/1.0/rc?cs=
4cb4e94bd5bb6&cb=INSERT_RANDOM_NUMBER_HERE"
target="_blank">
<img src="http://d.example.com/w/1.0/ai?auid=8&cs=
4cb4e94bd5bb6&cb=INSERT_RANDOM_NUMBER_HERE"
border="0" alt=""></a></iframe>
</noscript>
</div>
<!--Async ad request with multiple parameters.-->
<script type="text/javascript">
var OX_ads = OX_ads || [];
OX_ads.push({
"slot_id":"placeholderId",
"auid":"8",
"tid":"4",
"tg":"_blank",
"r":"http://redirect.clicks.to.here/landing.html",
"rd":"120",
"rm":"2",
"imp_beacon":"HTML for client-side impression beacon",
"fallback":"HTML for client-side fallback"
});
</script>
<!-- Fetch the Tag Library -->
<script type="text/javascript" src="http://d.example.com/w/1.0/jstag"></script>
Some other content here.
</body>
</html>
Following #Rafa excellent answer, i'm using this code to invoke OpenX banners after the page loads. I'm using jquery as well and had to add a new replace call for the "document.write" that flash banners use, and replacing it with "$('#"+ oDIV.id +"').append" instead. I'm using a custom "my_openx()" call, to replace "OA_show()". My banners area called by the zone_id and are wrapped inside a div, like this:
<div id="openx-4"><script>wm_openx(4);</script></div>
It's working :)
<script type="text/javascript">
$is_mobile = false;
$document_ready = 0;
$(document).ready(function() {
$document_ready = 1;
if( $('#MobileCheck').css('display') == 'inline' ) {
$is_mobile = true;
//alert('is_mobile: '+$is_mobile);
}
});
function wm_openx($id) {
if($is_mobile) return false;
if(!$document_ready) {
setTimeout(function(){ wm_openx($id); },1000);
return false;
}
if(typeof(OA_output[$id])!='undefined' && OA_output[$id]!='') {
var flashCode,
oDIV = document.getElementById('openx-'+$id);
if (oDIV) {
// if it's a flash banner..
if(OA_output[$id].indexOf("ox_swf.write")!=-1) {
// extract javascript code
var pre_code_wrap = "<script type='text/javascript'><!--// <![CDATA[",
post_code_wrap = "// ]]> -->";
flashCode = OA_output[$id].substr(OA_output[$id].indexOf(pre_code_wrap)+pre_code_wrap.length);
flashCode = flashCode.substr(0, flashCode.indexOf(post_code_wrap));
// replace destination for the SWFObject
flashCode = flashCode.replace(/ox\_swf\.write\(\'(.*)'\)/, "ox_swf.write('"+ oDIV.id +"')");
flashCode = flashCode.replace(/document.write/, "$('#"+ oDIV.id +"').append");
// insert SWFObject
if( flashCode.indexOf("ox_swf.write")!=-1 ) {
//alert(flashCode);
eval(flashCode);
//oDIV.removeClass('hidden');
}// else: the code was not as expected; don't show it
}else{
// normal image banner; just set the contents of the DIV
oDIV.innerHTML = OA_output[$id];
//oDIV.removeClass('hidden');
}
}
}
//OA_show($id);
}
</script>
I was looking for this to load advertising from my openX server only when the advertising should be visible. I'm using the iFrame version of openX which is loaded in a div. The answer here put me on my way to solving this problem, but the posted solution is a bit too simple. First of all, when the page is not loaded from the top (in case the user enters the page by clicking 'back') none of the divs are loaded. So you'll need something like this:
$(document).ready(function(){
$(window).scroll(lazyload);
lazyload();
});
also, you'll need to know what defines a visible div. That can be a div that's fully visible or partially visible. If the bottom of the object is greater or equal to the top of the window AND the top of the object is smaller or equal to the bottom of the window it should be visible (or in this case: loaded). Your function lazyload may look like this:
function lazyload(){
var wt = $(window).scrollTop(); //* top of the window
var wb = wt + $(window).height(); //* bottom of the window
$(".ads").each(function(){
var ot = $(this).offset().top; //* top of object (i.e. advertising div)
var ob = ot + $(this).height(); //* bottom of object
if(!$(this).attr("loaded") && wt<=ob && wb >= ot){
$(this).html("here goes the iframe definition");
$(this).attr("loaded",true);
}
});
}
Tested on all major browsers and even on my iPhone, works like a charm!!

Categories

Resources