Well to answer your question, boarding starts about noon (sometimes a little earlier) and they let you come and go from the ship as you please until 7PM (i think.. might be 8PM) once you have your S&S card. It is great to be able to check in, drop your luggage off and then go back out and visit San Juan some more. This works great if you are staying in San Juan the day before the cruise. But your 5:40PM flight should be ok. Assuming it takes you an hour or so to collect your luggage (you won't need to go through customs in San Juan) and get a taxi to the ship. You should be on board before 8PM...
If you could get in earlier or the day before it would be better (why risk a flight delay) but if you have to take that flight it should work.
Carnival Cruise Lines:
Fantasy 90, Celebration 95, Victory 05, Conquest 05, Spirit 6/06, Freedom 6/08, Holiday 7/08, Victory 6/09, Valor 9/09, Dream 6/10, Splendor 8/10,Conquest 8/11,Magic 11/11,Triumph 4/12,Spirit 7/12,Freedom 11/12, Triumph 2/13 - The fire cruise, Magic 1/14
NCL Dream October 2006, RCCL Mariner OTS June 2007, Celebrity Silhouette 2013