There are a couple of reasons for Act 5 to open with a conversation between two minor characters who have not appeared in the play before this scene. It is important to realize that when Shakespeare names them "clowns," he makes it clear that part of his intent is comedic, but there is another function as well. First of all, their conversation serves to inform the audience about the nature of Ophelia's death. The two gravediggers are preparing Ophelia's grave, and one asks the other why Ophelia is being given a Christian burial. The other responds that the "crowner" (king) has determined what kind of burial she shall have. They go on to discuss the difference between an accidental death and a suicide, clearly suggesting that while it might seem that Ophelia committed suicide, she will be given a proper burial in sanctified ground. This conversation clears up the reader's or viewer's questions about what happened to Ophelia.
The second purpose of the scene is create a bit of comic relief after the heaviness of the end of Act 4. Act 4 is dominated by Laertes's anger and Claudius's plotting against Hamlet. They have divised a deadly plan to kill Hamlet in a fencing match. This scene provides a break before the plan and its deadly outcome comes to fruition. The two clowns tell jokes, use puns, sing inappropriate drinking songs, and engage in word play with Hamlet. Even Hamlet seems to enjoy the verbal sparing. But even the joking becomes serious as Hamlet, once again, turns the conversation to the realities of death--an ongoing theme of the play.