Is it bad practice to embed JavaScript into the body of HTML?

前端 未结 17 2404
梦谈多话
梦谈多话 2020-12-13 01:44

A team that I am working on has gotten into the habit of using

相关标签:
17条回答
  • 2020-12-13 02:01

    If you have an editor that can handle both HTML and JavaScript syntax simultaneously. And if you like to first read a few lines of HTML and then JavaScript cpde...sure. Go for it.

    0 讨论(0)
  • 2020-12-13 02:03

    It is valid and, depending on your server-side framework and the nature of the code, sometimes very difficult to avoid.

    0 讨论(0)
  • 2020-12-13 02:03

    It's one of many, many best practices that's as much about improving performance as it is about improving your approach to programming.

    Ultimately in web development, getting the product out matters the most!

    0 讨论(0)
  • 2020-12-13 02:05

    I assume that your team is doing this either because they want to insert a script dynamically, or that they are writing a script that will fire at page load.

    I wouldn't say there's anything wrong with doing this when ABSOLUTELY NECESSARY, (as long as it's in a CDATA block), but outside of that, I would recommend to your team that they use a script library like Prototype or jQuery, and keep the scripts external to the page. This is usually cleaner, and libraries will sometimes force a bit of cleanliness to the code, which I would bet isn't happening currently.

    I also wouldn't run any time-consuming functions in inline script tags, as these happen on page load, and as Jason stated above, could slow the load of the page. All script libraries have neat functions that allow you to do things on load of the page, and will give you the option of when in the page load to fire them, such as after the DOM is loaded.

    0 讨论(0)
  • 2020-12-13 02:09

    Actually, it's quite common. For example Google's analytics tracking code uses just this syntax:

    <script type="text/javascript">
      var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
      document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
    </script>
    

    If it's good enough for Google...

    0 讨论(0)
  • 2020-12-13 02:09

    However, it's also good in that you know the JavaScript code needed for a section of HTML is going to be there for it. Rather than having to assert and build up some inclusion at the top of the file.

    So, rather than "if you're going to use this HTML, make sure you import xyz.js" you can just include the HTML and be done with it.

    So, it's not necessarily horrible evil. Perhaps not spectacularly awesome, but not utterly terrible either. It kind of depends on the intent.

    0 讨论(0)
提交回复
热议问题