Тёмный

DO NOT use innerHTML - 2 BIG Reasons Why | Javascript Optimization Tips 

Dave Gray
Подписаться 317 тыс.
Просмотров 14 тыс.
50% 1

Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGrayWebDevRoadmap
Do not use innerHTML. This video shows 2 HUGE reasons why you should avoid innerHTML and use alternatives instead. Learn Javascript Optimization Tips for creating dynamic content.
🚩 Subscribe ➜ bit.ly/3nGHmNn
🚀 This tutorial is part of an Advanced Javascript Concepts tutorial series playlist:
• Advanced Javascript Co...
DO NOT use innerHTML - 2 BIG Reasons Why | Javascript Optimization Tips
(00:00) Intro
(00:05) Welcome
(00:16) Setup
(01:13) Reason #1 to stop using innerHTML
(02:17) A better solution
(04:50) Reason #2 to stop using innerHTML
(06:37) If you must use innerHTML, do this first!
📺 Referenced Tutorials:
10 Time-Saving Javascript Functions: • 10 Javascript Function...
📚 References:
MDN innerHTML: developer.mozilla.org/en-US/d...
MDN createElement: developer.mozilla.org/en-US/d...
MDN createDocumentFragment: developer.mozilla.org/en-US/d...
✅ Follow Me:
Twitter: / yesdavidgray
LinkedIn: / davidagray
Blog: yesdavidgray.com
Reddit: / daveoneleven
Was this tutorial about why you should stop using innerHTML in Javascript helpful? If so, please share. Let me know your thoughts in the comments.
#innerHTML #javascript #optimization

Наука

Опубликовано:

 

30 июн 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 77   
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
This video shows the 2 BIG reasons I avoid using innerHTML when creating dynamic content in my web apps. It also shows you alternatives that are much better and what you should do if you must use innerHTML to mitigate at least one of the major issues innerHTML has. Just getting started with Javascript? I suggest starting with my full 8 hour course video here: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-EfAl9bwzVZk.html
@kostiantynkarzhanov9216
@kostiantynkarzhanov9216 Год назад
Absolutely amazing channel! Dave, thank you so much for this tutorial! 💛
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're welcome!
@pjf7044
@pjf7044 2 года назад
Good stuff man. I like that you talk about things most of main stream does not. Subscribed
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
I appreciate that! Thank you! 💯
@jorgealfredocarvalho
@jorgealfredocarvalho 2 месяца назад
Dear Dave Gray In your java script code for the performance example, when you test the second version using Fragment, you are declaring and creating the HTML paragragh element inside the loop (10000 times) and it's allways the same variable. If you declare and create the variable outside the loop the code will be faster. In my computer its 39 vs 52 (-25%). I like your videos and learned a lot with you. You are a very good teacher. You master the subjects and you are very methodic in your teaching. Best regards from Portugal
@pulserudeus7968
@pulserudeus7968 2 года назад
thank you for this awesome information👏🔥 I wonder if you also have parallel load/code splitting 🙌
@BsiennKhan
@BsiennKhan 2 года назад
First channel I found of a kind that explains what to do and why for day to day scenario. Subbed and many thanks
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're welcome! 🙏💯
@vladislavamarkova8379
@vladislavamarkova8379 2 года назад
Thank you, Dave! 🙏 Really useful video on that topic. Indeed, innerHTML is tempting to use :) but after we are aware of the, so to say, side effects, it is good to look for such alternatives.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thanks for the comment and the kind words, Vladislava! 🚀
@vladislavamarkova8379
@vladislavamarkova8379 2 года назад
All deserved!! :)
@aya2222
@aya2222 2 года назад
Wonderful tutorial as usual!! I finished your advanced JS playlist so far!! It's advanced so sometimes it was really hard to wrap my head around but I read documentation, sometimes went back to basic JS, and wrote down and broke it down and I grabbed each concept and resolved it. Thank you so much. Btw, do you have any recommended book to deepen our understanding of advanced JS?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Glad to hear it! I'll keep adding to this list, too. Great question - while not specifically for Javascript, the book I recommend for rethinking how you write code is "Clean Code" by Robert C. Martin. The examples in the book are in Java, but the concepts are what is important. 💯
@aya2222
@aya2222 2 года назад
@@DaveGrayTeachesCode Thank you so much!! I will check the book!! And I will start your React tutorials after deepening my vanilla JS understanding!
@syamprasad6038
@syamprasad6038 2 года назад
very useful info, thanks a lot
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're welcome! 💯
@shafieejaddini368
@shafieejaddini368 2 года назад
Very useful, thanks!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're very welcome! 💯
@Derfinater
@Derfinater 2 года назад
Appreciate ya Dave.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you very much! 💯
@Knards
@Knards 2 года назад
Makes sense. And the 10 functions are a godsend
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Glad to hear you liked the reference to my Ten Functions video! 💯🚀
@sergiorey2049
@sergiorey2049 2 года назад
Great info!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you Sergio!
@VechTech
@VechTech 2 года назад
*Nice!*
@Kryptik33
@Kryptik33 2 года назад
Whoa, ok thanks for showing this. As a new developer, you are correct, it is VERY tempting to just use innerHTML, but I had no idea of the performance differences. Wow.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Right on! 💯🚀
@md.shariarkabir7350
@md.shariarkabir7350 2 года назад
subscribed your channel.. because content was fantastic
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you for the kind words!
@tonhom260
@tonhom260 2 года назад
Thank you teacher !!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You are welcome! 💯
@ahmad-murery
@ahmad-murery 2 года назад
Hello Dave, I think we can achieve a close result to using fragment by building the html string inside the loop and set it once finished to innerHTML instead of setting innerHtml on each iteration, this might be useful for generating templates where the template string can be changed easily instead of building it using js, I like using fragments and I like these kind of videos, Thanks Dave,
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Ahmad, thanks for your note. Yes, that would be an alternative. It would be interesting to measure the difference. With the parsing required of a comparable 10,000 elements for the innerHTML - even once might be a lot. I'm glad you like fragments! 💯
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
@@b0tm0de yes, if I remember correctly, the main point of this video is not use innerHTML inside the loop.
@joaoarthurbandeira
@joaoarthurbandeira Год назад
Hey, noob question, how would the code to this be? How can i first build the html string inside the loop and then only use innerHTML after? Thanks!
@ahmad-murery
@ahmad-murery Год назад
​@@joaoarthurbandeira Hello, Starting form the first example *createParas1* declare a variable to store your html code above the loop inside the loop append to that variable after the loop change the innerHTML let str = '' let i = 0 while(i < 10000) { str += `My value is ${i}` i++ } main.innerHTML = str the main performance issue comes from modifying the innerHTML inside the loop which will trigger the browser to update the DOM and recalculate the elements flow on each iteration I hope it helps
@kadumkomut537
@kadumkomut537 2 года назад
doing this way is even more faster than the fragments by a little fraction but one thing is it overlaps the buttons also. so we have to create another element and append to it. let list = ""; while(i
@MusicIsLifeFM
@MusicIsLifeFM 2 года назад
interesting point
@ocxigin9220
@ocxigin9220 Год назад
Thanks for sharing this important useful tips, I tried to use it recently and I was reading the docs to learn more about it. I also find setHTML() is mention as a better alternative but its still in experimental phase. have you used the setHTML() and do you really consider it a better alternative?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Nice question! MDN says setHTML incorporates sanitization to prevent XSS so yes, that would be better: developer.mozilla.org/en-US/docs/Web/API/Element/setHTML
@ocxigin9220
@ocxigin9220 Год назад
@@DaveGrayTeachesCode Exactly. I hope it get implemented
@guilhermecampos8313
@guilhermecampos8313 Год назад
Just one question: couldn't you just set the text content of the h1 element at 7:40? Why don't understand the need of creating a div in this case. Very good tips by the way. I'll watch more of your videos.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
We want to keep the functions separate. This way I can call the sanitize function wherever needed in my code without rewriting that logic.
@khanfaizan05
@khanfaizan05 3 месяца назад
Great
@mocococo2877
@mocococo2877 6 месяцев назад
As far as I know innerHTML also breaks the event listeners attached to the element. Or something like that :)
@samiullahsheikh5015
@samiullahsheikh5015 Год назад
Strapi (CMS) has the rich text option so If a data is coming from rich text field in html/mdx format, the only option left is to use inner html in ReactJS application. Can you suggest how to avoid inner HTML in that scenario? Moreover if we need to persist the formatting of rich text like bold text etc
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
It's not that it should always be avoided. In this tutorial, I demonstrated something I often see beginners do - use innerHTML inside of a loop. That makes it very slow. It can also be dangerous if you take user input and apply it to a document with innerHTML. The React docs explain this well as they describe React's dangerouslySetInnerHTML: reactjs.org/docs/dom-elements.html ..User input should therefore be cleaned in some way before set with these methods.
@kasmanialisaad
@kasmanialisaad 2 года назад
InnerHTML is a very powerful function. Very underrated. I think the performance section is inaccurate as your way was very inefficient. You can just loop and concat it to a string then place it in innerHTML. It should roughly be same as the create fragment if not better. Also that way to sanitize seems very useful. Thanks.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
I'd like to see a comparison. innerHTML still has parsing of the parent element to do. I agree that using a variable would help. My example does show the inefficiency of repeatedly calling innerHTML as I have witnessed some students attempt. I believe createElement and document fragment is more efficient. Thanks for the comment. 💯 UPDATE: I ran a comparison building a variable in the loop with only one innerHTML call afterwards. When there are no other elements in the parent element to parse, the duration is comparable to the recommended createElement and document fragment approach. That said, if the parent element had many more elements to parse, even one call to innerHTML could slow down. Thanks for the suggestion which allowed me to explore further! 🚀
@joaoarthurbandeira
@joaoarthurbandeira Год назад
@@DaveGrayTeachesCode Hey, noob question, how would the code to this be? How can i first build the html string inside the loop and then only use innerHTML after? Thanks!
@solanosolano424
@solanosolano424 Год назад
Hello, i've been wondering, but even taking in account the performance issue. Isnt innerHTML just better when we want to create complete static and even dynamic web page ? Seem to me that the more complex your page and the more innerHTML can help lesser the code and allow easy maintaining. ofc not using it on stuff like input, form. for exemple let takes this code : MENU CONTACT ABOUT the code above would need 3 document.createElement + 3 appendChild, then then 3 setAttribute for the list then appendChild, 1 for the ul etc... that seem really heavy just for a static/dynamic small html.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
The emphasis from this video - do not use innerHTML inside of a loop. It is also bad if you are inserting user input without cleaning it first. You can use innerHTML to lessen the code as you say, but it does not increase the efficiency.
@d.i.vonbriesen8464
@d.i.vonbriesen8464 Год назад
Hi there - i'll need to test this, and thanks for the clear sample. But, i noticed you used innerHTML inside the for loop, whereas in your improved version you appended only once. What if you instead did you += on the content, and then did the one innerHTML after the loop, to be consistent with the better exampll? Seems like a little bit of unfair comparison. Also curious why while instead of for...
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Other comments discuss these options as well and many variations do exist. My goal here was to go over a beginner mistake that I see frequently and provide a better recommended solution. innerHTML can be a risky proposition that beginners do not always use well.
@d.i.vonbriesen8464
@d.i.vonbriesen8464 Год назад
@@DaveGrayTeachesCode Wow- thanks for the quick response! I'm refreshing my knowledge on a lot of this, and even my students who are new to this get quickly addicted to innerHTML! I'm curious if you could have used fragment in the second part over div (in other words, put into fragment and then get value out, rather than a div, as you did in your example).
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
@@d.i.vonbriesen8464 good question! It has been months so I'd need to look at this code again. Give it a try!
@d.john.h
@d.john.h 2 года назад
This blows my mind. Holy hell that's fast.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
For sure! Thanks for the comment 💯
@ragjnmusic8765
@ragjnmusic8765 2 года назад
I get a whole HTML content from the PHP server side then I use inner HTML to display the content if I use textcontent it just show the HTML codes not the content, What shall I do
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Considering you are receiving preformatted HTML from the server and not creating the elements with Javascript, you should probably keep doing what you are doing.
@ragjnmusic8765
@ragjnmusic8765 2 года назад
@@DaveGrayTeachesCode yeah like I send values such as numbers for sql search queries then I get the rows insert them inside HTML elements(product name,price,product image) then retrieve them as text using fetch api, insert inside a div using innerHTML also I do all the server side sanitizations and validations
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
@@ragjnmusic8765 ok. Sounds like you are iterating over rows of results and inserting into pre-existing HTML elements. Calling innerHTML in a loop with every iteration is super slow and should be avoided. That's what this tutorial is all about. It shows a better way.
@ragjnmusic8765
@ragjnmusic8765 2 года назад
@@DaveGrayTeachesCode No I don't do any of that using with JS, I use JS for only send data ,retrieve data and display the data, I send values to the PHP server side there I do the SQL queries , returns the rows insert the rows values inside HTML elements(product name price img src ) . (Now it will come to JS) then it will be returned as a text to the JS I use fetch API to get the results then I use innerHTML to show the text when I put inside a div using innerHTML now It will be like normal product menu , if I use textContent it just shows the HTML as a text(raw text not as HTML tags), hope you understood
@TheEmperorXavier
@TheEmperorXavier 2 года назад
Wow
@joelarpin473
@joelarpin473 Год назад
Dude, you're my new best friend
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Duuuude! 💯
@joelarpin473
@joelarpin473 Год назад
@@DaveGrayTeachesCode lol
@Marius752
@Marius752 2 года назад
My friend, your 1st reason is invalid. The equal counterpart to your fragment way of creating content is to create an empty string += that string in a loop and then put that generated string with .innerHtml and you will see similar speed results. Or do your appends inside the loop.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
I have discussed this with others in the comments. I agree that your approach is an improvement, but I don't believe my example is invalid. I have witnessed too many beginners make this exact mistake. Thanks for the feedback! 🙏💯
@rao180677
@rao180677 2 года назад
The comparison is not right. On innerHTML you're inserting into the Dom on each loop execution. To be a fair comparison, you would need to add the htm to a sting on each loop and then add all the concatenated string into the Dom.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
That would be more efficient. I have seen beginning students write the example that I show. That's why I wanted to highlight that example. Thanks for the comment!
@suelingsusu1339
@suelingsusu1339 2 года назад
🙏🙏🙏🙏🖖🖖🖖🖖🖖🖖
@stevensavoie856
@stevensavoie856 2 года назад
Reason 1: use document fragments for efficiency. You may now skip to Reason 2 which was actually ok. Wish he labeled his sections properly. Annoying to sit through obvious content for the lack of descriptive timestamp section names.
@mahmoudk528
@mahmoudk528 Год назад
Thanks, Dave really, I Appreciate it. I wanna ask, what if I want to get from an API and I don't know how much element or data I will get? and I have to create a lot of elements ?please check this example: let colElement = document.createElement("div"); colElement.innerHTML = ` ${name} ` I hope you got what I'm saying. Thanks again for your beautiful content!;
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're welcome! I'm not quite following what you are asking based on your code, but there is more room to post code with questions like these in my Discord: discord.gg/neKghyefqh
@mahmoudk528
@mahmoudk528 Год назад
@@DaveGrayTeachesCode alright! good luck dave
Далее
Important differences between textContent and innerText
11:44
치토스로 체감되는 요즘 물가
00:16
Просмотров 1,1 млн
He turned a baseball into a stylish shoe😱
00:59
Просмотров 867 тыс.
Crazy Girl destroy RC CARS 👩🤪🚘🚨
00:20
Просмотров 4,4 млн
STOP Using Switch Statements! Use These Instead...
8:10
Projects Every Programmer Should Try
16:58
Просмотров 386 тыс.
Learn JavaScript DOM Traversal In 15 Minutes
14:44
Просмотров 220 тыс.
5 JavaScript Concepts You HAVE TO KNOW
9:38
Просмотров 1,4 млн
textContent vs innerHTML in the JavaScript DOM
4:38
Просмотров 50 тыс.
Is it safe to use innerHTML in JavaScript?
4:35
Просмотров 6 тыс.
ИГРОВОВЫЙ НОУТ ASUS ЗА 57 тысяч
25:33
Will the battery emit smoke if it rotates rapidly?
0:11