Is [removed] actually deprecated?

后端 未结 3 921
星月不相逢
星月不相逢 2020-12-03 18:50

I\'ve seen a bit of chatter about document.write being deprecated, but I\'m not sure exactly where this information came from. I did look it up in MDN, but ther

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 19:23

    No. It's just most often considered bad practice and almost as misused as eval.

    Read: Why is document.write considered a 'bad practice'?

    Quoting some important points from the linked question above:

    • document.write (henceforth DW) does not work in XHTML

    • DW executed after the page has finished loading will overwrite the page, or write a new page, or not work

    • DW executes where encountered: it cannot inject at a given node point

    Also as @JaredFarrish stated, deprecated is mostly a state of mind. It's a relic that most likely will never go away otherwise it'd break many sites - even the Traditional Google Analytics code uses DW.

    Obviously, functionality-wise it has been superseded long ago by proper DOM manipulation methods, and quoting the linked question above again: DW is effectively writing serialised text which is not the way the DOM works conceptually.


    To counterbalance, here's a list of where DW may be considered appropriate:

    • There's nothing wrong with DW, per se - it won't destroy your page if you use it appropriately;
    • It allows for easily fallbacking an external script to a local copy such as when loading jQuery from a CDN fails:

      
      
      
    • It's one of the easiest ways to insert external snippets in your page while keeping the code short (e.g. analytics). Note that systems such as Google Analytics now favor the asynchronous method - creating a script element through the document.createElement API, setting its properties and appending it to the DOM - rather than using its traditional document.write method.

    tl;dr:
    DW is easily misused, hence for real world use, prefer a proper DOM manipulation method whenever viable.

提交回复
热议问题