Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding a script tag to the DOM with javascript in IE with data attribute`

I need to add the following script tag to the DOM after a few things run on my page:

<script data-main="js/main" src="lib/Require/require.js"></script>

I know that optimally everything will be in my require file, but as of now i need to hotfix this to work in IE.

What i have that is working in FF/Chrome is:

var script = document.createElement('script');
script.setAttribute('data-main', 'js/main');
script.src = 'lib/Require/require.js';
document.getElementsByTagName('script')[0].parentNode.appendChihld(script);

However, IE doesn't like it when i try to set the attribute 'data-main' and therefore is not working.

How can i get around this and have it add the script element to the dom and have it load the script at the same time?

Thanks

like image 955
Troy Cosentino Avatar asked Jan 30 '13 03:01

Troy Cosentino


People also ask

Where do I put script tag in JavaScript?

put it inside the <head> tag with defer attribute, or even better make your script type='module' . It is 2022 now.

What is data attribute in JavaScript?

The data-* attribute gives us the ability to embed custom data attributes on all HTML elements. The stored (custom) data can then be used in the page's JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).

How fetch data attribute in JavaScript?

JavaScript access To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written. In the above case setting article. dataset.


1 Answers

this seems to work fine in IE as well:

var scriptTag = document.createElement("script");
scriptTag.type = "text/javascript";
scriptTag.src = "lib/Require/require.js";
scriptTag.setAttribute("data-main", "js/main");
( document.getElementsByTagName("head")[0] || document.documentElement ).appendChild( scriptTag );
like image 174
Sudhir Bastakoti Avatar answered Oct 13 '22 16:10

Sudhir Bastakoti