When they are still small their lungs are not very well develop that's why they have external gills. As the lungs start to develop more and more the external gills start to shrink and get absorb. Inside the eggs they are unable to go to the surface that's also why they have external gills.
Baby sharks that are actually inside the womb of the monther actually have external gills. Lungfish also have this.