<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>my tech blog &#187; javascript</title>
	<atom:link href="http://billauer.se/blog/tag/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>https://billauer.se/blog</link>
	<description>Anything I found worthy to write down.</description>
	<lastBuildDate>Thu, 12 Mar 2026 11:36:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.2</generator>
		<item>
		<title>Google ads: How to lose the wait</title>
		<link>https://billauer.se/blog/2009/05/google-ads-wait-speed-load-appendchild/</link>
		<comments>https://billauer.se/blog/2009/05/google-ads-wait-speed-load-appendchild/#comments</comments>
		<pubDate>Fri, 29 May 2009 08:47:09 +0000</pubDate>
		<dc:creator>eli</dc:creator>
				<category><![CDATA[Internet]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[absolute positioning]]></category>
		<category><![CDATA[appendchild]]></category>
		<category><![CDATA[google ads]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[scripts]]></category>

		<guid isPermaLink="false">https://billauer.se/blog/?p=233</guid>
		<description><![CDATA[Someone once told me that WWW stands for World Wide Wait. But when the page is held because the browser waits for a Google Ad to come in, that&#8217;s really annoying. I didn&#8217;t want that to happen in my site. So here&#8217;s the story about how to have the page displayed first, ads later. One [...]]]></description>
			<content:encoded><![CDATA[<p>Someone once told me that WWW stands for World Wide <strong>Wait</strong>. But when the page is held because the browser waits for a Google Ad to come in, that&#8217;s really annoying. I didn&#8217;t want that to happen in my site.</p>
<p>So here&#8217;s the story about how to have the page displayed first, ads later. One may argue that you want your money machine up (ha!) before giving away the goods. One could also argue that the ads coming in late will draw more attention. I say: A slow site is like no site.</p>
<p>And as with any story, the solution comes in the end. If you want to know who the killer is, and don&#8217;t care about the drama, just skip to the end.</p>
<h3>Trial #1: Absolute positioning</h3>
<p>Spoiler: This didn&#8217;t work for me. But it may work for you. I don&#8217;t know if it&#8217;s because I&#8217;m using a lot of Javascript in my page or not.</p>
<p>The idea was that if the browser doesn&#8217;t need to know what&#8217;s inside the ad box, it will go on rendering the page. Since an absolutely positioned section is out of the flow, and won&#8217;t change any other part&#8217;s placement, I hoped that the browser would be smart enough not to wait for the ads. Or stupid enough to overlook the inconsistency in scripting. I was wrong.</p>
<p>Anyhow, this is the code I used:</p>
<pre>&lt;div style="position: relative; height: 620px; width: 200px; overflow: hidden; "&gt;
&lt;div style="position: absolute; top: 0px; left: 0px"&gt;
&lt;script type="text/javascript"&gt;&lt;!--
google_ad_client = "pub-xxxxxxx";
google_ad_slot = "xxxxxxxx";
google_ad_width = 160;
google_ad_height = 600;
//--&gt;
&lt;/script&gt;
&lt;script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"&gt;
&lt;/script&gt;
&lt;/div&gt;&lt;/div&gt;</pre>
<p>The outer DIV allocates the necessary space on the page. The inner DIV is absolutely positioned, so no matter what comes in there, everything else will remain in place.</p>
<p>What really happened: IE6 went right on with the rest of the page, Firefox still waited for the ads to load. Even though IE played it nice this time, it&#8217;s actually a bug in IE.</p>
<p>The thing is, that I have a lot of Javascript embedded in my page. Since the Google ad code consists of Javascript itself, the browser must wait until that code is loaded before running any other Javascript code (which may, as far as the browser is concerned, depend on it). Firefox waited to prevent unpredictable execution of following Javascript code, IE just went on. Ignorance is bliss.</p>
<p>This way or another, the problem remains. I mean, even Microsoft will fix this bug some day.</p>
<h3>(non)-Trial #2:</h3>
<p>The idea is simple. If the Google ad code appears just before the closing &lt;/body&gt;, the browser must be pretty boneheaded to wait for it. So now the trick is to get the ad in the right place.</p>
<p>Proposed trick:  Create a &lt;div&gt; container at the end of  the document, and push it to its place with absolute positioning. With Javascript or without. This can be done only if one knows the exact pixel position in terms of the entire document. There is no safe way, that I know of, to get the absolute position of an element by its ID. Neither to get it into a known position within a containing block other than the one you&#8217;re currenly inside.</p>
<p>There are scripts out there which claim to do that, but they don&#8217;t rely on any standard. And getting a block of ads in the wrong place is too bad to risk.</p>
<p>And I haven&#8217;t even mentioned what happens when the page is resized. Unless all surrounding elements are nailed in place with absolute positioning, bad things can happen&#8230;</p>
<p>Anyhow, this method didn&#8217;t fit my case. I dropped it.</p>
<h3>Trial #3: Hijacking document.write()</h3>
<p>One widely proposed solution is to hack document.write(), which Google uses to implant the extra HTML. I don&#8217;t like it very much, because it&#8217;s well, hacky. But I tried. And then I saw what the script in show_ads.js produces:</p>
<pre>&lt;script src="http://pagead2.googlesyndication.com/pagead/expansion_embed.js"&gt;
&lt;/script&gt;
&lt;script src="http://googleads.g.doubleclick.net/pagead/test_domain.js"&gt;
&lt;/script&gt;
&lt;script&gt;window.google_render_ad();&lt;/script&gt;</pre>
<p>So show_ads.js writes a script that loads other scripts? Doing what? Call other?</p>
<p>This was just enough to scare me off. If hijacking means to recursively run scripts loaded by scripts, there&#8217;s a good chance to really mess things up. So I gave this idea up as well.</p>
<h3>Trial #4: Moving the DOM element</h3>
<p>This is the way to do it. Let the browser reach the ad segment at the end of the document, and then manipulate the document tree, moving the element to its right position. This is pretty intrusive, and it turns out that it pushes the browser&#8217;s tolerance to the limit.</p>
<p>But first, let&#8217;s look at the code. It has two parts. First, we put this where we really want the ads:</p>
<pre>&lt;div style="position: relative; height: 620px; width: 200px; overflow: hidden; "&gt;
&lt;div id="googletarget" style="position: absolute; top: 0px; left: 0px"&gt;
&lt;/div&gt;&lt;/div&gt;</pre>
<p>That&#8217;s pretty much like what I did in trial #1, with two important differences: The google ad isn&#8217;t here, of course, and I&#8217;ve given the inner DIV an ID, so I can target it later. Absolute positioning is still important, because I don&#8217;t want the page to flicker when the ad comes in.</p>
<p>Then, at the end of the document (before closing &lt;/body&gt;) we have:</p>
<pre>&lt;div style="display: none;"&gt;&lt;div id="googleads"&gt;
&lt;script type="text/javascript"&gt;&lt;!--
google_ad_client = "pub-xxxxxxx";
google_ad_slot = "xxxxxxxx";
google_ad_width = 160;
google_ad_height = 600;
//--&gt;
&lt;/script&gt;
&lt;script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"&gt;
&lt;/script&gt;
&lt;/div&gt;&lt;/div&gt;
&lt;script type="text/javascript"&gt;
document.getElementById("googletarget").appendChild(document.getElementById("googleads"));
document.getElementById("googleads").style.display="block";
&lt;/script&gt;</pre>
<p>That rings an old bell too. It&#8217;s exactly like the original script, now embedded in other DIVs and with an extra script snippet, which moves the ads to their right position using appendChild(). W3C is very clear about that appendChild() never duplicates a node, but moves it in case it&#8217;s already placed in the document tree.</p>
<p>And the DIV, to which the ads are loaded into, is wrapped by another DIV which is set to &#8220;display: none&#8221;. This makes them invisible in their original position, so nothing flickers at the bottom of the page and the scroll bars don&#8217;t get crazy. And even better, if the appendChild() fails (because the browser is old or primitive), the ads remain invisible. Which is rare enough to neglect businesswise, and harmless in terms of how badly we&#8217;ve messed up the page.</p>
<p>In IE6, it was necessary to set the display mode back to &#8220;block&#8221; after moving it. That&#8217;s what the line after the appendChild() is for.</p>
<p>By the way, &#8220;visibility: hidden;&#8221; wasn&#8217;t enough, because the Google data contains an IFRAME, which doesn&#8217;t respect the external DIV&#8217;s visibility status.</p>
<p>And in the extreme case, in which the browser doesn&#8217;t respect the &#8220;display: hidden&#8221; attribute, we will have some ugliness at the bottom of the page. Functionally, it&#8217;s still harmless, and graphically it&#8217;s not so bad compared with what such a browser&#8217;s user sees every day.</p>
<p>So, this looks like a bulletproof solution. Of course it worked on any fairly updated browser I tested with. What could possibly go wrong?</p>
<p>The answer came to me when I tried in on an Mozilla 0.99 (seven years old). Don&#8217;t think I&#8217;m using it for myself, but testing on a steam engine is a good way to find weak spots. In our case, moving the ads around caused the browser to display a blank page. All was fine just before the call to appendChild(), but then the page went blank, and the browser started to behave strangely.</p>
<p>This is bad news. I&#8217;m trying to make a page load slightly faster, and I might make it unloadable (to some) instead. Even if I don&#8217;t believe that someone really uses a browser from 2002, a new, cutting-edge and somewhat buggy browser might fall in the same hole.</p>
<p>The problem, as it turned out, is that the element I move around consists of scripts. Mozilla 0.99 executes the script once when it&#8217;s loaded, and once again when it&#8217;s moved. Modern browsers execute the script once. IE6 is in the middle: It indeed runs the script once, but <a href="http://www.trygve-lie.com/blog/entry/moving_a_script_ie_might" target="_blank">loads it twice</a>. Not harmful to the user, but this indicates that moving a script around is not an issue of the past.</p>
<p>It also looks like there <a href="http://groups.google.com/group/mozilla.dev.tech.dom/browse_thread/thread/58278ac296df88c3/af6ca92c11d7715d" target="_blank">was an issue with appendChild() and scripts </a> around the development of Firefox 3.1, but given the relatively little attention it got (and the fact that the relevant remark in the docs has vanished), I suppose this is a non-issue.</p>
<p>To see how the browser behaves, I wrote a small snippet:</p>
<pre>&lt;div id="taker"&gt;&lt;/div&gt;
&lt;p&gt;Hello, world&lt;/p&gt;
&lt;div id="loser"&gt;
&lt;div id="node"&gt;
&lt;script&gt;
alert("Script running");
document.write("I was first!");
&lt;/script&gt;
&lt;/div&gt;&lt;/div&gt;
&lt;script&gt;
var node = document.getElementById("node");
alert("Now swapping");
document.getElementById("taker").appendChild(node);
&lt;/script&gt;</pre>
<p>The idea is that the two rows swap places by virtue of appendChild(). The &#8220;script running&#8221; alert should appear only once, of course. On Mozilla 0.99 it popped up twice, and the page ended up with &#8220;I was first&#8221; written before and after &#8220;Hello world&#8221;, which sort-of explains why nothing worked with Google ads. Other browsers I checked, including Konqueror 3.0.0 from 2002 ran the script once, as expected.</p>
<h3>Conclusion</h3>
<p>The solution I picked was appendChild(), of course. But I also realize that moving around an element which contains a script pushes the browser to its limits. On the other hand, AJAX web sites are becoming increasingly popular, so browsers are more and more likely to support this properly in the future.</p>
<p>For my own use, I&#8217;ve decided to do this trick only on browsers I&#8217;ve tested. This is possible since the page is produced by a server-side script, which checks the browser version. This will make the page load slightly slower on non-mainstream browsers, but on the other hand, guarantee that the page loads at all.</p>
]]></content:encoded>
			<wfw:commentRss>https://billauer.se/blog/2009/05/google-ads-wait-speed-load-appendchild/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Why MySQL&#8217;s (SQL) DATETIME can and should be avoided</title>
		<link>https://billauer.se/blog/2009/03/mysql-datetime-epoch-unix-time/</link>
		<comments>https://billauer.se/blog/2009/03/mysql-datetime-epoch-unix-time/#comments</comments>
		<pubDate>Sun, 15 Mar 2009 14:58:24 +0000</pubDate>
		<dc:creator>eli</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[datetime]]></category>
		<category><![CDATA[epoch]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[time]]></category>
		<category><![CDATA[unix]]></category>
		<category><![CDATA[utc]]></category>

		<guid isPermaLink="false">https://billauer.se/blog/?p=34</guid>
		<description><![CDATA[I warmly recommend reading the comments at the bottom of this page, many of which go against my point. While I still stand behind every word I said, in particular for web applications (which I believe is the vast majority of MySQL use), the comments below make some valid points, and single out cases where [...]]]></description>
			<content:encoded><![CDATA[<div style="border: 2px solid #9b9; margin: 20px 5px 50px 5px; padding: 15px 5px 0 5px;"><i></p>
<p>I warmly recommend reading the comments at the bottom of this page, many of which go against my point. While I still stand behind every word I said, in particular for web applications (which I believe is the vast majority of MySQL use), the comments below make some valid points, and single out cases where DATETIME actually <b>is</b> the right thing.</p>
<p>
Needless to say, this is a discussion, and we&#8217;re all free to make our own mistakes.</p>
<p></i></div>
<h2>SQL DATETIME sucks</h2>
<p>MySQL, among other databases, has a column type called DATETIME. Its name seems to mislead people into thinking that it&#8217;s suitable for storing time of events. Or suitable for anything.</p>
<p>This is a general SQL thing, by the way, but I&#8217;ll demonstrate it on MySQL.</p>
<p>I often find this column type in other people&#8217;s database schemas, and I wonder if the designer gave it a thought before using it. It&#8217;s true, that in the beginning it looks simple:</p>
<pre>mysql&gt; CREATE TABLE stupid_date ( thedate DATETIME, PRIMARY KEY (thedate) );
Query OK, 0 rows affected (0.04 sec)

mysql&gt; INSERT INTO stupid_date(thedate) VALUES ( NOW() );
Query OK, 1 row affected (0.03 sec)

mysql&gt; SELECT * FROM stupid_date;
+---------------------+
| thedate             |
+---------------------+
| 2009-03-15 14:01:43 |
+---------------------+
1 row in set (0.00 sec)</pre>
<p>That was way too cute, wasn&#8217;t it? We also have the NOW() function, which fits in exactly, and puts the current time! Yay! Yay! And if the timestamp looks old-fashioned to you, I suppose there is a reason for that.</p>
<p>But wait, there are two major problems. The first one is that the time is given in the host&#8217;s local time. That was fair enough before the internet was invented. But today a web server can be a continent away. DATETIME will show you the local time of the server, not yours. There are SQL functions to convert timezones, of course. Are you sure that you want to deal with them? What happens when you want to move your database to a server in another timezone? What about daylight saving time? Local time is one big YUCK.</p>
<p><em>(Update: As commented below, the real stupidity is to use NOW(), and not UTC_TIMESTAMP(). The latter gives the UTC time, as its name implies)</em></p>
<p>Problem number two: Most applications don&#8217;t care what the absolute time is. The current time is commonly used to calculate how much time has elapsed since a certain event. To filter elements according to if they were X seconds before now. Is the user still logged in? Has 24 hours elapsed since the last warning email was sent? And so on.</p>
<p>&#8220;Solution&#8221;: The SQL language supplies a variety of COBOL-like functions to calculate whatever we can ask for. And also an opportunity to get things horribly wrong, because the SQL statement became way too complicated.</p>
<h2>Use POSIX time() instead</h2>
<p>Sorry, didn&#8217;t mean to scare you off. It&#8217;s really simple: Any modern operating system, even Windows, will readily supply you with the number of seconds since January 1, 1970, midnight, UTC (that is, more or less GMT). This is also called &#8220;seconds since the Epoch&#8221; or &#8220;UNIX time&#8221;.</p>
<p>No matter where the computer is, what timezone it uses or what programming language you&#8217;re using, this simple integer representation will show the same number at any given moment.</p>
<p>You can, in fact, obtain this number from MySQL directly:</p>
<pre>mysql&gt; SELECT UNIX_TIMESTAMP(thedate) FROM stupid_date;
+-------------------------+
| UNIX_TIMESTAMP(thedate) |
+-------------------------+
|              1237118503 |
+-------------------------+
1 row in set (0.00 sec)</pre>
<p>This means, that 1237118503 seconds elapsed since the Epoch (which is a global time point) until 14:01:43 in Israeli <span style="text-decoration: underline;">LOCAL time </span>of the day I wrote this post. So now we have an integer number to work with, which is handy for calculations, but things will still get messy if we try to move the database to another server.</p>
<h2>Store the number instead</h2>
<p>If we are interested in working with integers, why not store the integer itself in the database? We could go:</p>
<pre>mysql&gt; CREATE TABLE smart_date ( thedate INTEGER UNSIGNED, PRIMARY KEY (thedate) );
Query OK, 0 rows affected (0.00 sec)

mysql&gt; INSERT INTO smart_date(thedate) VALUES (1237118503);
Query OK, 1 row affected (0.00 sec)

mysql&gt; SELECT * FROM smart_date;
+------------+
| thedate    |
+------------+
| 1237118503 |
+------------+
1 row in set (0.00 sec)</pre>
<p>That wasn&#8217;t very impressive, was it? The first question would be &#8220;OK, how do I get this magic number, now that I don&#8217;t have the NOW() function?&#8221;</p>
<p>The short and not-so-clever answer is that you could always use MySQL&#8217;s UNIX_TIMESTAMP( NOW() ) for this. The better answer is that no matter which scripting or programming language you&#8217;re using, this number is very easy to obtain. I&#8217;ll show examples below.</p>
<p>As for the magnitude of this number, yes, it&#8217;s pretty big. But it will fit a signed 32-bit integer until year 2038. I presume that nobody will use 32-bit integers by then.</p>
<p>And finally, one could argue that DATETIME is convenient when reading from the database directly. True. But for that specific issue we have the FROM_UNIXTIME() function:</p>
<pre>mysql&gt; SELECT FROM_UNIXTIME(thedate) FROM smart_date;
+------------------------+
| FROM_UNIXTIME(thedate) |
+------------------------+
| 2009-03-15 14:01:43    |
+------------------------+
1 row in set (0.00 sec)</pre>
<p>And again, this is given in the computer&#8217;s local time. Which is fine, because it&#8217;s intended to be read by humans. In particular, humans who easily translate time differences between their server and themselves.</p>
<h2>Obtaining Epoch time</h2>
<p>Just to prove that it&#8217;s easy to know what the &#8220;Epoch time&#8221; is in any language, here are a few examples. Wherever it&#8217;s really simple, I&#8217;m showing how to convert this format to human-readable format.</p>
<p>In Perl:</p>
<pre>print time();
print scalar localtime time(); # Local time for humans</pre>
<p>In PHP:</p>
<pre>&lt;?php
echo time();
echo date('r', time() ); // Local time for humans
?&gt;</pre>
<p>In Python:</p>
<pre>from time import time;
print time();</pre>
<p>(note that the time is returned as a float number with higher precision)</p>
<p>In C:</p>
<pre>#include &lt;time.h&gt;
#include &lt;stdio.h&gt;

int main () {
  int now = time(NULL);

  printf("%d seconds since the Epoch\n", now);
  return 0;
}</pre>
<p>In JavaScript:</p>
<pre>&lt;script language="JavaScript" type="text/javascript"&gt;
now = new Date();
alert( now.getTime() / 1000 );
&lt;/script&gt;</pre>
<p>In this case, the time is shown with a fractional resolution.</p>
<p>The JavaScript example is not really useful for a database application, because the time is measured at the computer showing the page. In a website application, this is just anybody&#8217;s computer clock, which may be wrong. But it&#8217;s yet another example of how this time representation is widely available.</p>
<h2>Conclusion</h2>
<p>Drop those DATETIME columns from your tables, and use a simple, robust and handy format to represent time. Don&#8217;t let the database play around with a sensitive issue like time, and don&#8217;t risk getting confused by different functions when calculating time differences. Just because the DATETIME column type exists, it doesn&#8217;t mean there is a reason to use it.</p>
<p>Enjoy the database on what it&#8217;s best at: Storing and collecting information.</p>
]]></content:encoded>
			<wfw:commentRss>https://billauer.se/blog/2009/03/mysql-datetime-epoch-unix-time/feed/</wfw:commentRss>
		<slash:comments>93</slash:comments>
		</item>
	</channel>
</rss>
