The beginning phrase-"Kimi Ga Yo"-was originally written "Wa Ga Kimi"(窶ーテ、窶堋ェナ誰, also approximately translated to "My Lord"). As time passed, the form using "Kimi Ga Yo" spread. At this point in time "Kimi" meant "Monarch" or "Emperor". However, in a time without mass communication, to the common people the Emperor seemed to be an untouchable, unimaginable god, floating above the clouds and a thing of long ago legend or fairy tales. So, it is also possible that the lyrics praying for the long life of "My Lord" were separated from any sort of loyalty and used instead as a prayer for the continuation of peace. For this reason, when the peacefully Heian Period changed to the bloody Edo Period, the song once again became used as a simple celebration song among common people. To go along with this, the meaning of "Kimi" also underwent a transformation. For example, when the song was sung in celebration of a wedding, "Kimi" came to mean the groom and the song was used to wish for the groom's long life and his family's health.
Incidentally, the version of the song that was published in the Elementary Student's Song Book (First Edition) maintained by the Japanese Ministry of Education (released in 1881) was longer than the current version and surprisingly, there was also a second version. It was derived from an English Hymn.