script: Improve dirty propagation and fix script-layout synchronization.

This fixes race conditions whereby layout and script could be running
simultaneously.

r? @jdm 
cc @cgaebel 
This used to have a `{}` around a much larger section of code, but it was only necessary to scope this dynamic borrow. I narrowed the `{}`.