Using Javascript to Insert Javascript Based Widget

Perm url with updates: http://xahlee.org/js/js_insert_js_code.html

Asynchronous Javascript; Using Javascript to Insert Javascript

Xah Lee, 2010-10-30

This page shows you how to use javascript (js) to insert a html that contains js code and have that js code run. If you don't know how to insert a element using js, see: Adding HTML Content with Javascript.

The Problem

There are lots js based widgets today. For example, web share widget, Google search widget, Comment widget, twitter, facebook, amazon ads... etc. They let you easily add functionality to your site.

If your webpage is static html, or generated by php or content manager software, you can directly include these widgets at the right place at the server side. However, sometimes it is convenient to use a js to insert them. Because, you may want the location of the widget to be different for different pages. Or, only centain pages you want to include the widget, but you don't know which until the page is generated.

So, the solution is to use a client side js that insert these js widgets.

If you use a javascript to insert a js code xyz, will the newly inserted xyz script run?

It depends on how you construct the element to be inserted. If the 「<script...>...</script>」 is constructed using 「innerHTML = ...」, then it won't work. But if it is constructed as a DOM element, then it'll work.

Using innerHTML Does Not Work

First, let's see what happens if you don't do anything special.

Suppose you want to use js to insert the following js code.

<div class="xyz">
 <script type="text/javascript">alert("woot!");</script>

Suppose you do it this way:

var myElement = document.createElement("div"); // create new div element

myElement.setAttribute("class", "xyz"); // add a class attribute

// add html in the div element
myElement.innerHTML='<p>Fantastic!<\/p> <script type="text/javascript">alert("woot!");<\/script>';

// add the new element after the first p tag
document.body.insertBefore(myElement, (document.getElementsByTagName("p"))[0]);

It will fail in IE8, Google Chrome, Opera. (but works in Firefox 3.6.12).

You can see what your browser do here: insert_js.html. For a version where each js file is on its own page, see: js_insert_js.html.

Creating 「<script>」 Object by createElement

Here's how to make it work. It's easy. Instead of using 「myElement.innerHTML="<script>...</script>";」, you should create the “script” element as a DOM object, then you insert this object.

Here's a sample js code:

var ele = document.createElement("script");
ele.type = "text/javascript";

document.body.insertBefore(ele, (document.getElementsByTagName("p"))[0]);

Here's a test page using this code: js_insert_js_works.html.

Twitter Example

Suppose you want to insert this code:

<div class="twtr">
<a href="http://twitter.com/share" class="twitter-share-button" data-count="vertical" data-via="xah_lee">Tweet</a>
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>

It's a widget that shows a Twitter button with number of tweets of the page.

Here's how you do it in your js:

// insert a twitter div tag before element “cg”
function insertTwitter (cg) {
    var mdv = document.createElement("div");
    mdv.setAttribute("class", "twt");

    mdv.innerHTML='<a href="http://twitter.com/share" class="twitter-share-button" data-count="vertical" data-via="xah_lee">Tweet</a>';

    var ele = document.createElement("script");
    ele.type = "text/javascript";
    ele.src = "http://platform.twitter.com/widgets.js";


    document.body.insertBefore(mdv, cg);


// insert before the first p tag

Thanks to “idealmachine” and DVK. stackoverflow.com.

Do you want a emacs cookbook?

Recently, a new lisp book came out: LAND OF LISP (Book and Comics).

My emacs tutorial and elisp tutorial is sizable for a book. There's no emacs cookbook or elisp cookbook on the market. To turn it into a book, it probably will take half a year at least to add content, convert html to a format suitable for print, as well as a lot work to improve quality. If i write a emacs book, are you likely to buy it?

  • Yes, if it's good.
  • No, am not likely to spend money on emacs/elisp book.

(Vote on the side.)

emacs javascript template

Does anyone know a emacs template for javascript?

In particular, am looking for template for either YASnippet or AutoComplete.

one minute google or emacswiki search didn't find anything.

(am already using both js2-mode and js-mode (espresso mode), they don't appear to have name completion or template builtin.


TRON Light Cycle Optimal Stradgy

Perm url with updates: http://xahlee.org/math/tron_light_cycle.html

TRON Light Cycle Optimal Stradgy

Xah Recommends:
Amazon Kindle. Read books under the sun. Review

Xah Lee, 2010-10-29

Has anyone done research about the opitmal strategy for the TRON's light cycle?

tron lightcycles

Tron lightcycles

We assume it as a perfect-info mathematical game, on a n×n square grid. (think of the board in Go (game).) Suppose the cycles are red and blue. Red moves first. Each turn, the player moves one square edge. The first player that doesn't have legal move loses. Also, we suppose it's a board game, and both players knows the other's position exactly at all times. We also for now assume that the starting position is at the opposite corners of the board.

  • 2×2. Second player win.
  • 3×3. First player win.
  • 4×4. Second player win.
  • 5×5. First player win.

The pattern seems clear. On Odd boards (where there's a center spot), first player win. On even boards, second player win.

Now, if we assume that the starting position is on the opposite of the same edge, the situation is the same. If we assume they start on the middle of the opposite edges, the situation remains the the same too (when the edge is even, we assume they start at opposite nearest edge-center).

So, it looks like game isn't mathematically interesting.

Making the Game Mathematically Interesting

But what about on boards of various regular tilings?

triangular grid triangular grid

Triangular Grid

honey comb grid honey comb grid honey comb grid

Honeycomb tiling.

After a quick look, it seems the analysis is pretty much the same. Whoever can get to the center wins, and if there is no center, second player always win.

Now, what are some ways to make the game interesting, or introduce some handicap rules, so it's more mathematically complex?

On a Flat Torus

What if it's played on a Flat torus?

If we start with n×n torus (that is, square torus), i think the situation is the same. When n is even, you can think of this as both player's light cycle having the same speed and start at the same time. Each want to maximize his area. When they meet head to head, both have no choice but turn 90° and race side by side, and when they both traced a circle, then turn back and race to the other side, and repeat. Eventually, the situation is the same as n×n bounded square. The first player will first run out of space.

If n is odd in a n×n torus, then first player wins.

Now, what about a m×n torus, where m is “n+1”? ...

Other topogicaly variation worth thinking about are m×n Moebius Strip or Klein Bottle or projective plane the Cross-Cap.

Am guessing that they all does not matter because player's moves are local, so topology of the space doesn't matter.

So, to make it interesting, perhaps each player can have 2 cycles, placed across 2 opposite positions in a space. Each turn, he can move one of his cycle by 1 unit.

Own Wall Can be Passed?

Now, let's go back to the original bounded square on a n×n grid. What if, one can pass his own walls? This would force the game into a draw, because a player can just draw a small square and keep running inside it.

Placing Bombs

Perhaps at each turn, the player can delete one spot. (the second player should be the first allowed to do this) Or, pick a spot that only he can still pass (e.g. mark a spot of his own color). This can be thought of as throwing a bomb.

PS If you like to play light cycle, there are 2 very nice free ones:

GLtron screensot

GLtron screensot

What Am I Supposed to Do? Survive!

Tron: Legacy film trailer. Music of Daft Punk's 〈Derezzed〉.

Was this page useful? If so, please do donate $3, thank you donors!

Javascript Encode URL, Escape String

Perm url with updates: http://xahlee.org/js/js_encode_url.html

Javascript Encode URL, Escape String

Xah Recommends:
Amazon Kindle. Read books under the sun. Review

Xah Lee, 2010-10-29

This pages shows you how to use javascript to do percent encoding for URI.

There are these js functions to do encoding and decoding.

  • encodeURI, decodeURI
  • encodeURIComponent, decodeURIComponent
  • escape, unescape

encodeURI and encodeURIComponent

encodeURI and encodeURIComponent are used for encode a URI. The difference is that encodeURIComponent will also encode the “http://” part. Here's a sample uri:


The dash above is a en-dash, unicode 8211 (U+2013).




The “%E2%80%93” are hexadecimals E2 80 93, and is the byte sequence of the en dash char by utf-8 encoding.

For detail, see: Percent-encoding.

The “escape” Function

The “escape” is similar to encodeURI, but it is used to encode any string not just URI, and it only encode certain characters.

Here's its result.


Sample Template; Test Yourself

You can test these functions on strings that contain any unicode char or Chinese. e.g. 「° © ® ™ § ¶ † ‡ ※ ◀▶▲▼ ♤♧♡♢ 林花謝了春紅」 Here's a html template:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>test page</title>

<script type="text/javascript" src="mytest.js"></script>


Here's js template:

var uri="http://en.wikipedia.org/wiki/Sylvester–Gallai_theorem";


document.write( "encodeURI:\n");
document.write( encodeURI(uri) + "\n\n");

document.write( "encodeURIComponent:\n");
document.write( encodeURIComponent(uri) + "\n\n");

document.write( "escape:\n");
document.write( escape(uri) + "\n\n");

Was this page useful? If so, please do donate $3, thank you donors!


Autism Spectrum Quotient

So, i found this Autism Spectrum Quotient from Facebook.

(before talking about that, here's a side story: motherfuck scumbag facebook. So, i saw this Autism Spectrum Quotient test from friend's comment. Click, and as usuall, it asks to accessing fucking info. Why the fuck is that necessary? Copy the phrase “Autism Spectrum Quotient test”, google, bang, arrive at http://www.wired.com/wired/archive/9.12/aqtest.html right there first result. No fucking require my age, sex, sexual preference fuck. (See: Facebook's Ethics.))

Ok, back. Now, the test is available here: http://www.wired.com/wired/archive/9.12/aqtest.html. Here's a quote about the test:

Psychologist Simon Baron-Cohen and his colleagues at Cambridge's Autism Research Centre have created the Autism-Spectrum Quotient, or AQ, as a measure of the extent of autistic traits in adults. In the first major trial using the test, the average score in the control group was 16.4. Eighty percent of those diagnosed with autism or a related disorder scored 32 or higher. The test is not a means for making a diagnosis, however, and many who score above 32 and even meet the diagnostic criteria for mild autism or Asperger's report no difficulty functioning in their everyday lives.

My score is 30.

Agree: 2,4,7,13,16,19,21,22,23,41,42,43,45,46: 1 point
Disagree: 1,10,11,15,17,24,27,29,34,37,38,40,44,47,48,50: 1 point
Score: 30

land of lisp

Perm url with updates: http://xahlee.org/comp/land_of_lisp.html


Xah Lee, 2010-10-27

Conrad Barski's book 《The Land Of Lisp》 is out! LandOfLisp.com. The site features a music video, and a comics strip. Very well done!

land of lisp war

Bug War, from landoflisp.com.

Land of Lisp- The Music Video!

《Land of Lisp: Learn to Program in Lisp, One Game at a Time!》By Conrad Barski M.D. amazon

Spread the news, team lisp!

5 eyed elephant alien

Conrad Barski's “alien technology” lisp web-badge Source.


Google is evil; Apple is a monopoly; and Microsoft is the underdog

Recently this tweet has been going around:

Welcome to 2010: Java is a restricted platform; Google is evil; Apple is a monopoly; and Microsoft is the underdog.

who first said it?


3 Twitter Facts You'll Never Forget

Perm url with updates: http://xahlee.org/js/twitter_make_money_fast.html

3 Twitter Facts You'll Never Forget

Xah Recommends:
Amazon Kindle. Read books under the sun. Review

Xah Lee, 2010-10-26

New twitter realizations.

Mutual Following

Those with huge but about equal number following/followers, means they just do mutual follow. Actual readership is probably near 0. Most these are i think are “seo” shit. They get 10k followers to brag on their website.

There are 100M twitter accounts. Suppose 1% of twitter population are these mutual followers. Then, we have 1M accounts who all having about 1M followers. (M = mega = million) That's why we see so much sites bragging huge twitter followers.

Anyone who follows more than 100 probably isn't reading any of it. Suppose someone follows 100 accounts. Suppose each of these has 1 tweet with link per day. That's 100 links. I think it's safe to say that 90% of those who follows more than 100 twitter accounts only click on 1% of the links in the tweets.

This means, if you get followed by someone who follows huge number of other accounts (i.e. you are just a drop of water in his follow pool), and if his tweets doesn't seem to have anything to do with your interests, chances are, you've been hit for his “follower count increment”.

Many of “seo” shit accounts do the mutual-following. They follow you, and if you didn't follow back, in a couple of days, they unfollow.

Am pretty sure there are lots of “seo” software that does the random follow, wait, drop, stuff. They are likely automatically done by software (just web search for “twitter follow”, “twitter unfollow”, “twitter tools”, “twitter tracker”, “twitter tips” etc, you'll get lots things to read.)

Even though huge number of twitter followers may still mean zero readership, but the bragging right might be useful. For example, advertisers might fall for your “this blog has 10k twitter followers”.

Bots Penetration

It's trivial to write a automated twitter software (called bots). There are lots twit bots. If we assume 0.1% twitter account are bots, that means 1M accounts are bots. Actually, the bot account may be significantly higher. Around 2007, i read on Wikipedia that some 80% blogger accounts are spammer accounts. Am guessing perhaps 1% or even much more of twitter accounts are bots, or human assisted bots.

Also remember, all the blurbs and photos in the profile can be fake. It is incredibly easy to forget this fact. So, you should take this approach instead: unless you actually know the other person, or thru a real life friend, then consider any new tweet account a upfront lie.

Been using twitter for about few months now. The more i think about this, the sadder it become. Sure twitter has its uses, in keeping up with close friends, spreading news and info, as well as legitimate and practically useful marketing for reputable businesses. But am beginning to think that vast majority of it is pure worthless shit (e.g. 90% of the twitter traffic are never read by anyone.).

Was this page useful? If so, please do donate $3, thank you donors!

Why Do I Not Support the “Human Right” Concept?

Perm url with updates: http://xahlee.org/Periodic_dosage_dir/human_rights.html

Why Do I Not Support the “Human Right” Concept?

Xah Lee, 2010-10-11

Criticisms On “Human Rights”

For criticisms of “universal human rights”, i guess the topic is old. But Wikipedia provides some starting points if you are not already familiar with this

(i don't necessarily agree with the above in particulars... but am just citing well-established philosophies against the universal “human rights” concept) Here's some selected quotes from different parts of Wikipedia:

Philosophers who have criticized the concept of human rights include Jeremy Bentham, Edmund Burke, Friedrich Nietzsche and Karl Marx[citation needed]. A recent critique has been advanced by Charles Blattberg in his essay "The Ironic Tragedy of Human Rights." Blattberg argues that rights talk, being abstract, demotivates people from upholding the values that rights are meant to assert.[87] In his book After Virtue, Alasdair MacIntyre claimed the concept that all human beings have certain rights simply by virtue of being human was illogical, stated "the best reason for asserting so bluntly that there are no such rights is indeed of precisely the same type as the best reason which we possess for asserting that there are no witches and the best reason which we possess for asserting that there are no unicorns: every attempt to give good reasons for believing there are such rights has failed."[88]

The concept of inalienable rights was criticized by Jeremy Bentham and Edmund Burke as groundless. Bentham and Burke, writing in the eighteenth century, claimed that rights arise from the actions of government, or evolve from tradition, and that neither of these can provide anything inalienable. (See Bentham's "Critique of the Doctrine of Inalienable, Natural Rights", and Burke's "Reflections on the Revolution in France"). Presaging the shift in thinking in the 19th century, Bentham famously dismissed the idea of natural rights as "nonsense on stilts". By way of contrast to the views of Burke and Bentham, the leading American revolutionary scholar James Wilson condemned Burke's view as "tyranny."[41]

Master-slave morality is a central theme of Friedrich Nietzsche's works, in particular the first essay of On the Genealogy of Morality. Nietzsche argued that there were two fundamental types of morality: 'Master morality' and 'slave morality'. Master morality weighs actions on a scale of good or bad consequences unlike slave morality which weighs actions on a scale of good or evil intentions.

Why Do I Not Support the “Human Right” Concept?

What right? Right with respect to what? Who gave you the right? God? I don't believe in a god, and in particular, i don't believe The Gods from Abrahamic religions (Islamism, Juadaism, and Christianity with its tens of factions).

When a animal, say, cat, eats a sheep, play with it under its paw before a jugular bite, does the sheep has a right? Who does the justice? you? When a wasp, lay eggs in spider's paralyzed body, so her offsprings can eat the spider alive from the inside, does the spider get rights? When the US, wrote universal human rights in its constitution, while importing blacks as slaves, where is the right? When George W Bush, made hundred thousands of Iraq civilians dead, where is the right?

All human animals are born “equal”? How so? Is a natural retard equal to your ability to work? Does he have equal chances? Does he really have equal opportunity? Should he deserve equal earning as you? Do you, give half of your income to those homeless or lazybums you see everyday on street corners?

I believe food is good, pleasure is good, pain and suffering is no good, and i believe that my good and bad to be about the same as other human animals. I believe that if i punch you in the face, you gonna punch back. We want prosperity, and this prosperity can come thru rational, responsible, dealings, same with conflicts.

If George Bush is to kill few hundred thousands of people, or when US Americans eradicated the native Americans out the face of this earth, i prefer the the reason given to be “because i like it, i am the king now”, than with believing in human rights, or manifest destiny.

The “human right”, is a moral fiction concocted out of ether much like religion. As a piece of untruth, it spreads woe and disaster, in a indirect way but with far-reaching consequences.

Was this page useful? If so, please do donate $3, thank you donors!


Torture Porn and Stupid Morality; Saw VI Review

Perm url with updates: http://xahlee.org/Periodic_dosage_dir/t1/saw.html

The Art of Torture: a Photographic Tour

Xah Lee, 2006-10, ..., 2010-08-14

Shotgun collar

Shotgun collar.

Jaw splitter

Jaw-splitter. This device snaps open jaws, set to a timer.

ice shower torture

Ice shower.

ice shower torture

Ice Shower turned sculpture.

head snapper

Skull Snapper. The victim is supposed to retrieve a key that were surgically placed in one of his eyes. A scalpel is provided for amenity.

razor wrist-trap

One-way razor wrist-trap.

body chain torture

Chain thru body. The victim is supposed to free himself by ripping off his punctured flesh.

ribcage ripper

Rib ripper. The victim is supposed to dip her hand into the acid to retrieve the key. Else, the harness that is attached to her ribs will rip her ribs apart.

ripped ribcage

The aftermath.

modern rack torture device

Modern Rack. The victim's limbs will be twisted beyond twistability by a mechanical force, and lastly, the neck as well.

These images are screenshots or photos from the movie series Saw. (Images taken from Wikipedia)

Sawamazon is a movie made by Americans. Its theme and central attraction, is explicit depiction of artful torture. By artful, it is meant that torture is taken as a art form, where the devices are ingenious, and the victims have to suffer the most possible pain before death, and mostly have to initiate or self-inflict the pain themselves, in the hope of escape. (e.g. sawing off their own leg, gouge their own eye, dipping hand in acid ...)

The Saw series, started in 2004, and because of huge profit, has been making a sequel each year. Saw III is released in 2006, again to huge success. Saw IV is planned to release in 2007.

In the USA culture, explicit enjoyment of torture is ok, but nakedness is not ok. For example, Janet Jackson exposed one of her breast on TV for a few seconds, that caused a nation-wide controversy with few milions dollars fine to TV networks and also a change in US law and live broadcast rules. See nakedness — a American crime.


Just watched the torture porn movie Saw VI amazon today. I love the torture scenes, but otherwise despise all other aspect of it. Americans, with their infatuation of justice and human rights, yet still love torture like every other human animal, had to create this twisted theme of justice to subconsciously justify their enjoyment of a graphic torture story. The Saw series is a huge money maker.

This shallow, twisted, theme of justice is very offensive to me. For example, you know how insurance company has a formula to calculate the insurance rates, coverage, for each person, based on their health, age? That's very rational, fair, and justified. But in Saw VI, it implies such insurance policy is not moral, and the person who “invented” this insurance formula is used as a victum for us to enjoy the torture show. You know how some people are addicted to drugs, who otherwise might have a good life? So, “Saw” makes fun of this. In Saw's theme, it says these people need to be tortured so that they “wake up” and realize the value of life. As another example, another justification to torture people is on those rich or well-to-do who are un-ethical or criminal in business or practices (e.g. Predatory lending). The victums are not always offenders of some crass morality. Some are almost random, playing on human vengence. Torturers also get tortured, as some sorta vindication that “you need to test yourself”.

In general, the film is about a demented guy who torture others. He considers himself to be some sort of justice giver or teacher in helping his victums. He thinks his victums “deserve” it. His reasons are certain lose pop morality. These brainless moral thoughts are typical of the uneducated masses.

The Saw series of movies insults intelligence, insults education, insults moral philosophy.

Of torture porn films, i rather enjoyed The Devil's Rejects amazon and Hostel: Part II amazon

The Devil's Rejects is a cult classic. Featuring a bunch of demented fucks of culturally American “midwest” types, crazy for the sake of it. Weird and funny. The “Hostel: Part II”, is just pure torture porn, without some moral shit. In Hostel II, i particularly like the protaganist chick Beth, who, when facing death, made a choice that transformed herself from a victum to villain. She is beautiful, intelligent, and courageous. The type of woman i love.

Was this page useful? If so, please do donate $3, thank you donors!