{"rowid": 316, "title": "Have Your DOM and Script It Too", "contents": "When working with the XMLHttpRequest object it appears you can only go one of three ways: \n\n\n\tYou can stay true to the colorful moniker du jour and stick strictly to the responseXML property\n\tYou can play with proprietary \u2013 yet widely supported \u2013 fire and inject the value of responseText property into the innerHTML of an element of your choosing\n\tOr you can be eval() and parse JSON or arbitrary JavaScript delivered via responseText\n\n\nBut did you know that there\u2019s a fourth option giving you the best of the latter two worlds? Mint uses this unmentioned approach to grab fresh HTML and run arbitrary JavaScript simultaneously. Without relying on eval(). \u201cBut wait-\u201d, you might say, \u201cwhen would I need to do this?\u201d Besides the example below this technique is handy for things like tab groups that need initialization onload but miss the main onload event handler by a mile thanks to asynchronous scripting.\n\nConsider the problem\n\nOriginally Mint used option 2 to refresh or load new tabs into individual Pepper panes without requiring a full roundtrip to the server. This was all well and good until I introduced the new Client Mode which when enabled allows anyone to view a Mint installation without being logged in. If voyeurs are afoot as Client Mode is disabled, the next time they refresh a pane the entire login page is inserted into the current document. That\u2019s not very helpful so I needed a way to redirect the current document to the login page.\n\n\n\nEnter the solution\n\nWouldn\u2019t it be cool if browsers interpreted the contents of script tags crammed into innerHTML? Sure, but unfortunately, that just wasn\u2019t meant to be. However like the body element, image elements have an onload event handler. When the image has fully loaded the handler runs the code applied to it. See where I\u2019m going with this?\n\nBy tacking a tiny image (think single pixel, transparent spacer gif \u2013 shudder) onto the end of the HTML returned by our Ajax call, we can smuggle our arbitrary JavaScript into the existing document. The image is added to the DOM, and our stowaway can go to town.\n\n

This is the results of our Ajax call.

\n \"\"\n\nPlease be neat\n\nSo we\u2019ve just jammed some meaningless cruft into our DOM. If our script does anything with images this addition could have some unexpected side effects. (Remember The Fly?) So in order to save that poor, unsuspecting element whose innerHTML we just swapped out from sharing Jeff Goldblum\u2019s terrible fate we should tidy up after ourselves. And by using the removeChild method we do just that.\n\n

This is the results of our Ajax call.

\n \"\"", "year": "2005", "author": "Shaun Inman", "author_slug": "shauninman", "published": "2005-12-24T00:00:00+00:00", "url": "https://24ways.org/2005/have-your-dom-and-script-it-too/", "topic": "code"}