javascriptasynchronousmobilemedia-queriesadvertisement-server

Conditionally loading ad code based on device screen size using javascript


How to conditionally display ads (via an ad server) to different screen size for mobile devices?

I don't want to set the display to none for hiding content, as this will skew the ad impression count.

I want to inject the ad code (eg. ) into div using client-side javascript without jQuery.

For example,

<div id="adzone"></div>

If width < 768px
   inject ad code for mobile
else
   inject ad code for tablet

How do I implement this idea?

And how will situation be handled when device rotation taking place when device width changes from less than 768px to grater then 768px?


Solution

  • So, two things to cover:

    One way that you could do this would be to simply have the JS capture the screen size and to then report that to your server when asking for an ad. The server can then make the decision on which ad to serve.

    You talk about screen rotation and you have tagged media-queries in your question. @media are CSS (not JS) features that allow you to tailor your look/feel based on screen size. It would be up to you to ensure that the ads you serve can be somehow displayed both vertically and horizontally - you wouldn't want to have to load new ads every time the device changes orientation.

    Detecting screen size completely accurately can very on device and how it is reported. However, for JavaScript world, this SO post covers what you need to know.