The flux-ratio anomalies observed in multiply lensed quasar images are most plausibly explained as the result of perturbing structures superposed on the underlying smooth matter distribution of the primary lens. The cold dark matter cosmological model predicts that a large number of substructures should survive inside larger haloes but, surprisingly, this population alone has been shown to be insufficient to explain the observed distribution of the flux ratios of quasars’ multiple images. Other haloes (and their subhaloes) projected along the line of sight to the primary lens have been considered as additional sources of perturbation. In this work, we use ray tracing through the Millennium II simulation to investigate the importance of projection effects due to haloes and subhaloes of mass m > 108 h−1 M⊙ and extend our analysis to lower masses, m≥ 106 h−1 M⊙, using Monte Carlo halo distributions. We find that the magnitude of the violation depends strongly on the density profile and concentration of the intervening haloes, but clustering plays only a minor role. For a typical lensing geometry (lens at a redshift of 0.6 and source at a redshift of 2), background haloes (behind the main lens) are more likely to cause a violation than foreground haloes. We conclude that line-of-sight structures can be as important as intrinsic substructures in causing flux-ratio anomalies. The combined effect of perturbing structures within the lens and along the line of sight in the Λ cold dark matter (ΛCDM) universe results in a cusp-violation probability of 20–30 per cent. This alleviates the discrepancy between models and current data, but a larger observational sample is required for a stronger test of the theory.