I am trying to understand same origin policy better. From what I understand same origin policy restricts code from one "origin" not access data from another "origin". What I am trying to understand is the context of this code. I can see that code across two tabs (example1.com and example2.com) cannot access data in each other's DOM. What about a page that loads code from both these sites? Is the restriction/security still hold in that case? This is a very valid use case as every site nowadays has code loaded from twitter, Facebook, google+ at the very least in addition to code from example1.com. So can code from twitter access the cookies set by example1.com? Or does same origin policy hold even in this case?
Of course in this case I am assuming the code is loaded from twitter, Facebook directly and not relayed from the example1.com server. I am also guessing the danger of XSS exists if the example1.com is relaying the code for twitter, Facebook etc. Am I right?
If I am right, how does the browser separate out the dom data for code loaded from each site when they are all loaded into the same page? How does it keep track of which data is allowed to be accessed by which code?