from what I've read, there were three major events/factors in the rapid increase in nationalist sentiment:
- the loss of the Spanish fleet, as Socrates said, which drastically reduced Spain's ability to defend and communicate with the colonies
- the failure of Spanish troops to defeat the British invasion of La Plata (local troops were the ones who defeated them), breaking the idea that Spain was protecting them from foreign conquest
- and the change of regime in Spain during the Peninsular campaign. When the Bourbons were removed, the common feeling was that Joseph Bonaparte was not a legitimate king. Juntas (local military governments) formed across the colonies, claiming that sovereignty had (temporarily, at first) reverted to the people, establishing precedent for republicanism and political separation from Madrid. These juntas gradually turned towards self-government, rejecting the pro-Bourbon resistance in Spain, the liberal constitution of 1812, etc.
after that, the idea of independence was too strong for the weakened Spanish to keep control. Removing the Napoleonic Wars would take care of all three of these things, ensuring Spain had a far greater ability to protect their colonies, maintaining the idea of security and legitimacy, and preventing a power vacuum which would allow the rise of independantists.
Luck would probably still run out for Spain, though. Spain was allied to France even before Napoleon's rise to power, which means there might still be some conflict with Britain. And the 19th century was chaotic, it would be surprising if Spain avoided any civil conflict. Even if Spain
did avoid both external defeats and domestic chaos, the stifling colonial regulations, distance from Spain, and any number of issues with colonial rule would strengthen independence movements.