While loading a JS SDK on our website I was trying out few different ways. I noticed that Snippet 1 causes CORS error, while Snippet 2 loads the same script on same page without any issues.
Snippet 1 (Using document.body.appendChild, throws CORS exception)
const url = 'https://www.example.com/sdk.js';
const scriptTag = document.createElement('script');
scriptTag.setAttribute('crossorigin', 'anonymous');
scriptTag.setAttribute('src', url);
document.body.appendChild(scriptTag);
Snippet 2 (Using parentNode.insertBefore, no CORS exception)
const element = document.getElementsByTagName('script')[0];
const scriptTag = document.createElement('script');
scriptTag.async = !0;
scriptTag.crossorigin = 'anonymous';
scriptTag.src = 'https://www.example.com/sdk.js';
element.parentNode.insertBefore(scriptTag, element);
I tried to find why the behaviour is different for each case, but could not find any reason for it.
Can someone point out to me why I see this behaviour?