Ask Your Question
3

How can JavaScript be used to add the defer or async attribute to script tags that are generated dynamically?

asked 2022-02-07 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-12-10 09:00:00 +0000

pufferfish gravatar image

To add the defer or async attribute to script tags that are generated dynamically using JavaScript, you can follow these steps:

  1. Create a new script element with document.createElement('script') method.

  2. Set the source attribute of the script element with the URL of the script file using setAttribute('src', 'script.js') method.

  3. Set the defer or async attribute of the script element using setAttribute('defer', 'true') or setAttribute('async', 'true') method.

  4. Append the script element to the document using document.body.appendChild(script) method.

Here is an example code that adds defer attribute to a dynamically generated script tag:

var script = document.createElement('script');
script.setAttribute('src', 'script.js');
script.setAttribute('defer', 'true');
document.body.appendChild(script);

Similarly, you can use async attribute instead of defer to make the script execute asynchronously.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-02-07 11:00:00 +0000

Seen: 10 times

Last updated: Dec 10 '22