问题
How can I add just crossorigin to the following <script>
tag?
The goal is to only add the crossorigin and not added the anonymous or use-credentials attributes.
Current output:
<li><div id="somevalue"><script type="text/javascript" async src="some-source"></script></div></li>
Desired output:
<li><div id="somevalue"><script type="text/javascript" crossorigin async src="some-source"></script></div></li>
(function() {
var scriptTag = document.createElement('script');
scriptTag.type="text/javascript";
scriptTag.async=true;
scriptTag.src="some-source";
var divTag = document.createElement('div');
divTag.id='somevalue';
divTag.append(scriptTag);
var liTag = document.createElement('li');
liTag.append(divTag);
var ulList = document.getElementById('footer-menu');
ulList.append(liTag);
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu" id="footer-menu">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
回答1:
Simply use setAttribute :
(function() {
var scriptTag = document.createElement('script');
scriptTag.type="text/javascript"
scriptTag.async=true
scriptTag.setAttribute('crossorigin','anonymous')
scriptTag.src="some-source";
console.log(scriptTag);
})();
By the way, crossorigin attribute is not meant to be empty : https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes
来源:https://stackoverflow.com/questions/50420726/how-to-add-just-crossorigin-to-script-tag