9.3 Why doesn’t this [terminal or window-system setup] code work in my init file, but it works just fine after Emacs starts up?

During startup, Emacs initializes itself according to a given code/file order. If some of the code executed in your init file (see How do I set up an init file properly?) needs to be postponed until the initial terminal or window-system setup code has been executed but is not, then you will experience this problem (this code/file execution order is not enforced after startup).

To postpone the execution of Emacs Lisp code until after terminal or window-system setup, treat the code as a lambda list and add it to emacs-startup-hook (or tty-setup-hook in Emacs 24.4 and newer). For example,

(add-hook 'emacs-startup-hook
          (lambda ()
           (when (string-match "\\`vt220" (or (getenv "TERM") ""))
             ;; Make vt220's "Do" key behave like M-x:
             (global-set-key [do] 'execute-extended-command))))

For information on what Emacs does every time it is started, see the lisp/startup.el file.