简体   繁体   中英

DOM behaviour when we append/remove element from DOM

Whenever I have to display a popup, I am used to adding an empty div tag and a button on the web page like

<div id="popupDiv"></div>
<input type="button" id="popupButton" />

Then I hook on a button click event using jQuery and use ajax to call on the server method which returns me the partial view html content as shown below which I bind to the div element using jQuery html method:

$('#popupButton').click(function () {
            $.ajax({
                cache: false,
                data: {},
                dataType: 'html',
                type: 'GET',
                url: '/Inquiry/Inquiry/GetPopupHtml',
                success: function (data) {
                    $('#popupDiv').html(data);
                },
                error: function (data) {
                    alert('Oops! An error has occured!');
                }
            });
});

I also refer a script file in partial view to add functionality on the popup at the end of my html file. I add all the javascript inside

$(document).ready(function(){
//my code inside script
})

I have the following questions

Do we really need to write my javascript inside $(document).ready()?

Does DOM gets reloaded when we append/remove element from DOM or When we add html content within an existing element( popupDiv ) iewhen I am using $('#popupDiv').html(data) to display popup content?

Do we really need to write my javascript inside $(document).ready()?

No, provided that you are loading your javascript after the dom is ready. You can either add the script tag near the closing body tag so first the dom will be ready, then it will load the script; else you can also use window.onload .

Does DOM gets reloaded when we append/remove element from DOM

No, if the dom gets reloaded, the entire page will be reloaded. During append/remove, only the delta changes are updated.

The document ready is used to delay the script execution until the page has been parsed into the DOM. If you put your scripts at the bottom of your page, you do not need the document ready.

As far as if the DOM is "reloaded", no. You are appending elements directly to the dom when you use html() or append(). jQuery takes the elements and appends them, or if you give it html, it will convert the html to elements within a DOM Fragment, and append that fragment to the DOM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM