Not Everything has to be done Server-side

Here is a little JavaScript trick I did to randomly include LeanPub embed (e.g., like the one in the right sidebar

Here is a little JavaScript trick I did to randomly include LeanPub embed (e.g., like the one in the right sidebar).

<script>
jQuery(document).ready(function(){
  var slugs=['rapid-prototyping-with-js','ohmyjs'];
  var index =Math.round(Math.random());
  jQuery('#leanpub').html('<iframe width="188" height="400" src="https://leanpub.com/'+slugs[index]+'/embed" frameborder="0" allowtransparency="true"></iframe>');});
</script>
<div id="leanpub"></div>

Not everything has to be done server-side! The added benefit of this snippet is that it loads  the embed after the rest of the page (thanks to jQuery(document).ready wrapper). This dramatically reduces website loading speed (in my case 0.5-2s), because an iframe generation is one of the most time consuming browser operations.

To use it with your LeanPub books just replace slugs with your books’ ones in the array, and paste into HTML page (or WordPress widget like I did). In case you have more than two books, multiple

Math.random()

by the number of books, e.g. for 10 books:

Math.random()*10

 

Author: Azat

Techies, entrepreneur, 20+ years in tech/IT/software/web development expert: NodeJS, JavaScript, MongoDB, Ruby on Rails, PHP, SQL, HTML, CSS. 500 Startups (batch Fall 2011) alumnus. http://azat.co http://github.com/azat-co

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.