When to use setAttribute vs .attribute= in JavaScript?

后端 未结 9 2375
闹比i
闹比i 2020-11-22 11:44

Has a best-practice around using setAttribute instead of the dot (.) attribute notation been developed?

E.g.:

myObj.setAttr         


        
9条回答
  •  忘掉有多难
    2020-11-22 12:31

    Interesting takeout from Google API script regarding this:

    They do it like this:

    var scriptElement = document.createElement("script");
    scriptElement = setAttribute("src", "https://some.com");
    scriptElement = setAttribute("nonce", "https://some.com");
    scriptElement.async = "true";
    

    Notice, how they use setAttribute for "src" and "nonce", but then .async = ... for "async" attribute.

    I'm not 100% sure, but probably that's because "async" is only supported on browsers that support direct .attr = assignment. So, there's no sense trying to sestAttribute("async") because if browser doesn't understand .async=... - it will not understand "async" attribute.

    Hopefully, that's a helpful insight from my ongoing "Un-minify GAPI" research project. Correct me if I'm wrong.

提交回复
热议问题