Morocco actually did undergo modernization under Moulay Hasan (r. 1873-1894), but as was typical of Egypt and Tunisia around the same time, the capital for these modernizing projects came from Europeans, who then called in the loans. This increased European influence in the country (imagine a 19th century IMF, really). His successor, Moulay Abd al-Aziz (r. 1894-1908) came to the throne at age fourteen, and proved weak as France gobbled up Morocco. So you'd need a different successor for starters, and a bit of haggling with European geopolitics.
The French were eager to take over Morocco, but it wasn't a sure thing. Avoid the Fashoda Incident. After Fashoda, Britain backed French domination of Morocco to ease tensions between the two. And the French eagerly took up the deal. In 1902, French recognized Italian interests in Libya in return for recognition of French interest in Morocco. Even after Fashoda, it took until 1904 for Britain to recognize Morocco as an area of French interest, in the Entente Cordiale. French then moved onto Spain, where they divided things up in October 1904. And then came German opposition. So have the Germans do a little better, not enough to take over, but enough to offset the French, and it's doable. The Fashoda Incident would have to go, to get Britain onside. Or possibly, you could go back into the 1890s and have the Germans back the Italian claim over Tunisia, which they were miffed about the French taking.