Comic relief is the easy answer. Poor Ophelia has gone mad, and in that madness she has drowned herself. How heavy and very sad is her demise, and as a contrast to her death, and in a way to cast light upon it, the humor is shocking and funny at the same time.
But there is more going on here than just comic relief. The clowns are engaged in a kind of discourse that mocks intelligence. There is a cold, scientific and legalistic sense about their banter that makes fun of a reasoned attitude toward death. It's as if they are making fun of Hamlet's kind of cerebral approach to existence and its opposite.
If they were to hear Hamlet say, in all seriousness, "To be, or not to be, that is the question..." they'd have another good laugh. You can just hear Clown One quoting his creator: "Life's a tale told by an idiot, sweet Prince, relax!"
First, the scene serves as a break from the overwhelmingly somber and depressing events in the preceding act. The audience receives some respite from all the drama and sorrow depicted in Act lV: Hamlet had had a serious fallout with his mother, Polonius was killed, Hamlet escaped sure death, Ophelia committed suicide, and Laertes arrived in Denmark with the intention of avenging his father's death.
By this time, the audience is surely in a sour mood and there is even worse to come. The light relief provided by the clowns not only provides the break the audience needs, but also fortifies them against the more dramatic events looming ahead.
In addition, this scene is important since it provides insight into the nature of Ophelia's death and considers a number of important theological questions which might have been something widely discussed at the time. The clowns first consider whether Ophelia's death was the result of suicide or accident and, if it was suicide, whether she should be given a Christian burial. It is clear from their discussion that suicide does not allow for a Christian burial and that this is confirmed in law. However, Ophelia, who they believe committed suicide, is to be buried with full Christian rites.
The suggestion by the first gravedigger is that those of wealth and influence are favored in this regard. Since Ophelia was Polonius's daughter,and thus a gentlewoman, the privilege of a full Christian burial was extended to her even though the two clowns believe she killed herself. In this regard, the two mention the following:
Will you ha' the truth on't? If this had not been
a gentlewoman, she should have been buried out o'
Why, there thou say'st: and the more pity that
great folk should have countenance in this world to
drown or hang themselves, more than their even
The obvious conclusion is that the two feel aggrieved about the fact that such a privilege should be given at all; there is clearly no equality, and the first clown expresses regret about the unfairness of it all.