Load External JavaScript on Desktop Only - javascript

I have went through a ton of answers, and I can not get anything to work for me. Please be patient and specific as I am a newbie when it comes to using JavaScript.
I am attempting to get an external JavaScript file to load on Desktop only. Below is the code I am currently using, but it is not working. Can someone please help me achieve this.
<script>
(function() {
if( window.innerWidth > 600 ) {
var theScript = document.createElement('script');
theScript.type = 'text/javascript';
theScript.src = 'www.siteminds.net/m/1.6/mind_loader.php?pid=y2w6z8B3N31&cast_id=v1532315&autoplay=1&avname=jackie&wc=1&avnum=15&band_type=av';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(theScript, s);
}
})();
</script>
I am placing this code in the head section, however, the script is not running.
The website is responsive using respond.js. I also added enquire.js in an attempt to use that method (which I also couldn't get to work)

Probably, the main issue is that you must include the protocol on the URL so:
'www.siteminds.net/m/1.6/mind_loader.php?pid=y2w6z8B3N31&cast_id=v1532315&autoplay=1&avname=jackie&wc=1&avnum=15&band_type=av'
needs to be:
'http://www.siteminds.net/m/1.6/mind_loader.php?pid=y2w6z8B3N31&cast_id=v1532315&autoplay=1&avname=jackie&wc=1&avnum=15&band_type=av'
Your code could also fail if there were not already some script tags. This version is not vulnerable to that:
<script>
(function() {
if( window.innerWidth > 600 ) {
var theScript = document.createElement('script');
theScript.type = 'text/javascript';
theScript.src = 'http://www.siteminds.net/m/1.6/mind_loader.php?pid=y2w6z8B3N31&cast_id=v1532315&autoplay=1&avname=jackie&wc=1&avnum=15&band_type=av';
var head = document.getElementsByTagName('head')[0];
head.appendChild(theScript);
}
})();
</script>
Note: a test for innerWidth > 600 is not even close to a fail-proof way to detect a desktop installation as even a tablet in landscape mode will pass that test.

This is what ended up working for me.
<script>
var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
if ( width > 600) {
document.write('<script src="//www.siteminds.net/m/1.6/mind_loader.php?pid=y2w6z8B3N31&cast_id=v1532315&autoplay=1&avname=jackie&wc=1&avnum=15&band_type=av" async><\/script>');
}
</script>

Related

Facebook pixel is not rendering on my site

I am trying to add a facebook pixel to my ruby on rails application. Facebook asked me to add this javascript to the head of my page - so I added it to the application.html.erb layout in the head section:
<!-- Facebook pixel -->
<script>(function() {
var _fbq = window._fbq || (window._fbq = []);
if (!_fbq.loaded) {
var fbds = document.createElement('script');
fbds.async = true;
fbds.src = '//connect.facebook.net/en_US/fbds.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(fbds, s);
_fbq.loaded = true;
}
_fbq.push(['addPixelId', 'thisismysecretid']);
})();
window._fbq = window._fbq || [];
window._fbq.push(['track', 'PixelInitialized', {}]);
</script>
<noscript><img height="1" width="1" alt="" style="display:none" src="https://www.facebook.com/tr?id=938407189542791&ev=PixelInitialized" /></noscript>
Then I tested my pages by using the google chrome facebook pixel tester extension - and it continually says no pixel was found. When I look at the generated source from my application - i actually don't see any of this inside the head of the page, so I assume that's why its not working - but why isnt it being rendered or processed?
SO! Why?! What am I doing wrong? Many thanks for all your support.
Well - the problem was - the page I was testing this on was not being rendered using templates from rails - so this code was never being run! Silly but true - all fixed now. The code itself was absolutely fine.

Javascript and Responsive Design

I have this piece of javascript for my responsive site (See below).
In a nutshell, I don't want it to display (meaning I don't want this javascript to execute) when the screen size is below 480 (mobile phone). How would I do that? I tried using display:none for the div that it's in, but the script still executes and the Hello Bar still shows. Any ideas? Thanks.
<script type="text/javascript" src="//s3.amazonaws.com/scripts.hellobar.com/511972d9264fc5de88a0b9d919dc42d757a0d2ad.js"></script>
Here's the website: http://www.thesandiegocriminallawyer.com
Here's the HTML (near the bottom):
<div class="hello_bar">
<script src="//s3.amazonaws.com/scripts.hellobar.com/511972d9264fc5de88a0b9d919dc42d757a0d2ad.js" type="text/javascript">
</div>
Measure the screen width and only attach the hellobar script if its wider than 480:
Replace:
<script type="text/javascript" src="//s3.amazonaws.com/scripts.hellobar.com/511972d9264fc5de88a0b9d919dc42d757a0d2ad.js"></script>
With:
<script type="text/javascript">
var swidth = (window.innerWidth > 0) ? window.innerWidth : screen.width;
if (swidth > 480) {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "//s3.amazonaws.com/scripts.hellobar.com/511972d9264fc5de88a0b9d919dc42d757a0d2ad.js";
document.getElementsByTagName('head')[0].appendChild(s);
}
</script>
http://jsfiddle.net/xusH3/
There are 2 solutions I can think of:
Load the script dynamically by checking the width of the screen first and then loading the file in an asynchronous way if needed.
Wrap the content of your script file in a condition that is based on the width of the screen/document (the file will be loaded anyway but won't run anything if screen is below 480)
The first way is better, while the second can solve headache if you need your code to be available immediately when the page loads
A sample for loading script in an async way is:
<script>
function loadScript(url){
var js, fjs = document.getElementsByTagName('script')[0];
js = document.createElement('script');
js.src = url;
fjs.parentNode.insertBefore(js, fjs);
};
if(window.innerWidth>480){ //here you should check for the width (this check is not necessarily cross browser)
loadScript("//s3.amazonaws.com/scripts.hellobar.com/511972d9264fc5de88a0b9d919dc42d757a0d2ad.js");
}
</script>

Loading jquery depending on window size

I am new to javascript and struggling with this basic problem - I want to load jQuery only if the window size is below a certain threshold (i.e., the mobile version doesn't require it). For the desktop version, jQuery must load in the <head> and not the <body>, as the content above the fold requires it.
I've tested the loop, and I'm getting the screen width printed on the page, but jQuery isn't loading. I'm sure it's a basic syntax problem but I just can't see it! Any help would be most appreciated. :)
<script type="text/javascript">
function loadjsfile(filename){
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
}
var w=window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
if (w > 899){
document.write("screen Width: " + w);
loadjsfile("http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js");
}
</script>
you've created the fileref variable that contains your script tag object but you never add it to the DOM, thus it never loads.
function loadjsfile(filename){
var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
//add this line
document.getElementsByTagName('head')[0].appendChild(fileref);
}

Using jQuery to insert Javascript code into a DIV

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);

A bookmarklet to disable the tinymce visual editor?

I'm looking for a bookmarklet to disable the tinymce visual editor. This is to say, some code that could be pasted into the address bar to disable the editor (and also bookmarked).
Anyone have any ideas?
The page I want to use it on is using an older version of TinyMce, I think the same version that is used on this page: http://www.imathas.com/editordemo/demo.html
Just to reiterate, I want to remove the TinyMce editor and leave the textarea.
If you would like to see the functionality I am talking about, you could also visit this example page: http://www.matracas.org/sentido/tinymce/examples/full.html and click on the enable / disable buttons below the editor.
The problem here is that the syntax relies on knowing what editor id to put into the .get() function.
tinyMCE.get('elm1').hide();
tinyMCE.get('elm1').show();
The bookmarklet would ideally just use tinMCE's show / hide functionality, but it would work for all editors on a page.
Here you go!
javascript:(function(){var arr=Object.keys(tinyMCE.editors);for(var i=0;i<arr.length;i++){try{tinyMCE.editors[arr[i]].remove();}catch(e){}}})()
More visibly pleasing, but same code:
javascript:
(function(){
var arr=Object.keys(tinyMCE.editors);
for(var i=0;i<arr.length;i++){
try{
tinyMCE.editors[arr[i]].remove();
}
catch(e){
}
}
}
)()
I start all my bookmarklets with jQuery, although this may work better as a greasemonkey script depending on what you're trying to do.
javascript:
function loadScript(url, callback){
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = url;
var done = false;
script.onload = script.onreadystatechange = function() {
if( !done && ( !this.readyState
|| this.readyState == "loaded"
|| this.readyState == "complete") )
{
done = true;
callback();
script.onload = script.onreadystatechange = null;
head.removeChild( script );
}
};
head.appendChild(script);
}
loadScript("http://code.jquery.com/jquery-latest.js", function(){
jQuery('.mceEditor').remove(); }
I have added a TinyMCE remover to my bookmarklet collection:
http://richardbronosky.github.com/Perfect-Bookmarklets/tinymce.html
It has one major advantage over the others I have seen. It restores the content of the textarea back to what was in the source. I don't know if others have experienced this, but we have a web admin to our CMS and TinyMCE, when removed leaves the code altered. I have resolved this.
Here is the code:
for(var i=0;i<tinymce.editors.length;i++){
var tmpId=tinymce.editors[i].id;
var tmpVal=document.getElementById(tmpId).value;
tinyMCE.execCommand("mceRemoveControl",true,tmpId);
document.getElementById(tmpId).value=tmpVal
}
Also on github:
https://github.com/RichardBronosky/Perfect-Bookmarklets/blob/master/tinymce.html

Categories

Resources