The original meaning of the word gag was to prevent someone from speaking, either by covering the mouth or through a legal restraint such as a gag order.
The jocular use of gag originated in the theater to describe times when an actor inserted an unscripted, and often humorous, line into a play.
It was called a gag because the ad lib often caused fellow actors to lose their focus and become speechless.
That’s why a vocal restraint and a joke are both called a “gag”.