The best way to pet a dog is to let the dog make first contact, and then slowly rub the dog's chest and under his head. Many dogs respond poorly to fast movements and pats on top of the head.
Always get permission from the owner before petting a strange dog. Let the dog sniff your closed fist. Some dogs feel threatened by movements over their head, so move your hand underneath the dog to rub his chest and lower neck. Pay attention to the dog's response, and pace your pats accordingly. Small dogs are more comfortable if you crouch or kneel down closer to their level.