Fix js error and optimize code