Optimize For loops

don't recalculate if it's not necessary
Add ScriptDocument class