Home > Software design >  How to add attributes without value when dynamically generating elements with jQuery append?
How to add attributes without value when dynamically generating elements with jQuery append?

Time:06-16

I am using this code to append a script element to my DOM:

$("body").append($("<script />", {
    src: "https://www.googletagmanager.com/gtag/js?id=<?php echo $block->getGoogleTagManagerId(); ?>",
    async: true
}));

This adds the script like this:

<script src="https://www.googletagmanager.com/gtag/js?id=xyz" async="async"></script>

I was expecting this:

<script src="https://www.googletagmanager.com/gtag/js?id=xyz" async></script>

Are both ways identical ? Will both work?

I worked around it by setting it like this:

$("body").append($("<script />", {
    src: "https://www.googletagmanager.com/gtag/js?id=<?php echo $block->getGoogleTagManagerId(); ?>",
    id: "googletagmanager_script"
}));
$("#googletagmanager_script").prop("async", true);

But does it even make a difference?

CodePudding user response:

They're equivalent. async is a boolean attribute. To make it true, you just add it to the element, and the value is not really significant.

If a boolean attribute is present, its value is true, and if it's absent, its value is false.

HTML5 defines restrictions on the allowed values of boolean attributes: If the attribute is present, its value must either be the empty string (equivalently, the attribute may have an unassigned value), or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

But for backward compatibility, browsers generally don't enforce this restriction.

jQuery uses the form of attribute="attribute" as its canonical format when it creates boolean attributes with true values. If you want just attribute, you can use an empty string as the value:

$("body").append($("<script />", {
    src: "https://www.googletagmanager.com/gtag/js?id=<?php echo $block->getGoogleTagManagerId(); ?>",
    async: ""
}));
  • Related