0

I want to add advertising to my website. But the ad company not provide the responsive solution.

All I got was two script sources for pc and mobile.

web

728*90
<script src="http://xxx_728_90&ad_type=banner"></script> 

mobiles

320*50
<script src="http://xxx_320_50&ad_type=banner"></script>

It will be ok if I have two versions for pc and mobile but I only have one. My question is how to change the ad script source base on screen size.

Vuong Tran
  • 31
  • 1
  • 5

2 Answers2

0

You don't necessarily have to implement the script as HTML. You can script your scripts!

To do this you will need a mechanism to decide whether you are running on a desktop or mobile. For simplicity, I will use the screen object, which contains useful data about the physical device. This approach is a bit naive, consider using the viewport and listen to resize events to respond to changes to the window size (if the library can tolerate being re-loaded).

const isDesktop = screen.width > 700;
const script = document.createElement('script');
script.src = 'http://xxx_' + (isDesktop ? '728_90' : '320_50') + '&ad_type=banner';
document.body.appendChild(script);
Community
  • 1
  • 1
Seth Holladay
  • 8,951
  • 3
  • 34
  • 43
  • I got this error: Uncaught DOMException: Failed to execute 'appendChild' on 'Node': Only one element on document allowed. – Vuong Tran Dec 29 '16 at 05:52
  • @VuongTran Quick typing = bugs. :) I edited the answer, try again. – Seth Holladay Dec 29 '16 at 05:55
  • another one: net::ERR_NAME_NOT_RESOLVED – Vuong Tran Dec 29 '16 at 06:01
  • @VuongTran That is because the URL you gave in the question is invalid. I am not sure where `http://xxx_728_90` came from, but I can't fix that. You will need to figure out the correct URL for the advertising library and use it. I assume the `xxx` is supposed to be replaced with some kind of site ID. – Seth Holladay Dec 29 '16 at 06:12
  • xxx was example. I fix it. But the ad not display :( – Vuong Tran Dec 29 '16 at 06:26
0

Finally I found the solution.

<script src="http://media.krxd.net/derek/postscribe.js"></script>
<div class="container">
<div id="ad"></div>
 <script>

 // jQuery used as an example of delaying until load.
  $(function() { 
     if ( $(window).width() > 739) {      
  //Add your javascript for large screens here 
  var str='728_90';
} 
else {
  //Add your javascript for small screens here 
  var str='320_100';
}
    // Build url params and make the ad call
    postscribe('#ad', '<script src=xxx'+str+'&ad_type=banner><\/script>');
  });

</script>
</div>
Vuong Tran
  • 31
  • 1
  • 5