Jordan Carter
Jordan Carter

Reputation: 1336

Using <style> and <script> in html...is it really so bad?

I really think that it would be beneficial to my workflow if I could just include a fully-functional component with a single php function call. Something like

ddl();

Which would produce an HTML drop down list, fully styled and functional. With external resources, I need to worry about including the JavaScript and CSS to get this working properly, but if I just included all of that within the ddl() function itself, it would make things much easier.

So something like:

<?php
function ddl(){
  <style>
     .ddl{
           //style
      }
  </style>
?>
  <div class="ddl">
     <!-- my drop down list -->
   </div>
   
 <script>
     //Do ddl functionality
 </script>
<?php
}

What are the real drawbacks to doing things this way? Is it worse for performance?

Upvotes: 1

Views: 136

Answers (2)

Jesper
Jesper

Reputation: 2094

  1. Easier to manage cache, which will reduce bandwidth usage
  2. No code duplication
  3. Better practice for scalability purposes - maybe you have a interaction designer, graphical designer and a software developer. You wouldn't want everyone to work on the same file

Upvotes: 0

Paurian
Paurian

Reputation: 1402

For small projects - one to three pages - you probably won't ever notice much of an issue. Especially if you never duplicate functionality. However, if you want a scalable application, you really need to separate form from function. Style sheets are actually easier to maintain by looking at the relationship of styles amongst themselves. JavaScript is better managed in larger chunks than embedded scripts.

If you ever decide later to scale an application that has embedded styles and JavaScript, you have the headache to deal with separating these out - especially when you want to reuse functionality. And if you forget to remove a style tag from within your HTML, or worse - a style attribute - it could override your CSS file changes down the road, so the clean-up is really important.

There's also a caching benefit by placing JavaScript and CSS in separate files. When you have a function or a style that's repeated throughout your web app, the browser only has to load the code once per file. If, however, you've embedded it in every page, the browser has to reload all that every time.

For easier maintenance, clarity of code and caching speed, I vote you should always keep these separated from your HTML/PHP.

Upvotes: 2

Related Questions