Dynamic loading of script shows different behaviour for same JS file

zer0Id0l :

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?

Edu Ruiz :

The only difference I see running your code is the on pointed by @Pointy on the comment, the first script generates:

<script crossorigin="anonymous" src="https://www.example.com/sdk.js"></script>

the second one:

<script async="" src="https://www.example.com/sdk.js"></script>

running on my console, so probably the crossorigin is responsable for the cors error. (the same happened on console, btw)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29627&siteId=1