Malicious scripts are code fragments that, among other places, can be hidden in otherwise legitimate websites, whose security has been compromised. They are perfectly baited for victims, who tend not to be suspected because they are visiting trusted website.
Put simply, the solution to use to stand out of attacks is to avoid giving client applications, such as web browsers, bad code to run in the first place. You can prevent this from happening by using a number of scenario-specific strategies, such as protecting against cross-site scripting attacks, protecting against compromised code libraries, and following best practices to prevent web servers from being compromised. The idea with these strategies is to shift left, and to ensure that security controls are applied to your software from the beginning stages of the software development lifecycle (SDLC).