major update, completely changed implementation
fixed bug: root.document wasn't passed to the function in node/browser environments