Javascript best practice use [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm looking for the best practice use of external private Javascript file.
I have a project with many different HTML files.
My question is what is the best practice, is it to have 1 .js file for all HTML pages or should I have a seprate .js file for each HTML?
I still nor clear if it is feasible at all the have 1 .js file for many different HTML pages, how can I use DOM capabilities?

This is a rather broad question and it really depends on how you structure your project.
This day and age, my general advice would be: structure it in whatever way it makes it easier to work with, but when building/deploying/whatever merge all the files together and minimize the result.
This results in easy development for you and maximum performance for the end user. Also, don't forget about proper caching headers and a timestamp in the URL for that JS file.
This advice actually applies to CSS files as well.

I agree with #Vilx-'s answer, but I suspect the question is a little more basic than that.
On each HTML page, you can simply link to a script containing site-wide functions and variables, and perhaps also a script unique to that page. For example, if you had special functionality on an About Me page, you could link to it like:
<!-- Global functions and variables -->
<script type="text/javascript" src="/scripts/global.js"></script>
<!-- Functions and variables that only apply to this page -->
<script type="text/javascript" src="/scripts/about-me.js"></script>
That way, you still have your utility functions in global.js, but you control the specific page using about-me.js.
Another way you could do this is by storing all of your JavaScript in a single file, but executing relevant functions inline on the corresponding page.
Main.js
function homepage(){
// do things specific to the homepage
}
function aboutMe(){
// do things specific to about me
}
function contactUs(){
// do things specific to the contact page
}
About-Me.html
<!-- Global functions and variables -->
<script type="text/javascript" src="/scripts/main.js"></script>
<script>
// Execute the relevant function defined in main.js
aboutMe();
</script>
The best way is really what fits your application. If it's a large, complex application then you'll want to have separate files, but you'll probably want to concatenate them before publishing the project. If it's a small personal project, then there's no harm in simply structuring your project the way you see fit.

Related

what is the best method to bind dom events on website based on es6? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
this days i build a custom website and i use es6 classes to perform most of the js work.
as i try to keep the site fast i do not use any js framework and try to keep it vanilla.
I wonder, what should be faster and more efficient to maintain, shall i just create lots of document.addeventlistener on single js file or shall i create class for binding events and use lile:
class dom_events {
constructor() {
document.body.addEventListener('click', this.clickHandler, false );
}
clickHandler = event => {
// do stuff
document.body.removeEventListener('click', this.clickHandler);
}
}
or maybe using some "object" functions like:
var dom_events = {
bind: function(){
document.body.addEventListener('click', this.clickHandler, false );
}
}
moreover, shall i use one big file or is it better to use one js file for each module of the website?
since i'm about to bind about 500 events, i would love to hear from your knowledge and experience
From my experience, multiple js files can slow down your website because the browser sends different requests to the server. Also, if your js file is very large, then it might cause the same problem.
If you want to add multiple js files, you can use <link rel="preload" href="path to your js file..." as="script">.
If your js file is not very large, then you can use script tag in your HTML file. This reduces the load and makes your webpage faster.

Is it a bad practice to add large parts of HTML that's not required to be visible when the site loads using javascript? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I need to have 2 popup modals in each HTML file to allow users to login and sign up, and was wondering if it was possible to simple have a common js file to add it using innerHTML or a similar method instead of typing it out in every HTML file. Would this cause any performance issues?
Neither should cause major issues with performance, especially since you're not trying to show these models until the user has interacted with the page.
You're mentioning that you would have to copy-paste this HTML chunk into every file. This would violate the DRY principle, and cause you to be left maintaining copy-pasted HTML in many different files, which is never a good thing. In this scenario, I would go for dynamically generated HTML.
If you want to dynamically generate the HTML yourself (without a templating library, etc), then I would avoid .innerHTML as much as possible - it's convenient, but it's also easy to fall into security pitfalls with it. Prefer using the Javascript built-in DOM APIs.
I personally like to use this helper function to make the DOM APIs easier to use.
function el(tagName, attrs = {}, children = []) {
const newElement = document.createElement(tagName);
for (const [key, value] of Object.entries(attrs)) {
newElement.setAttribute(key, value);
}
newElement.append(...children);
return newElement;
}
// USAGE
const customElement = el('div', { id: 'myId', class: 'myClass' }, [
el('p', {}, ['Some Text']),
el('br')
])
// The above element will get added to the body, and has the following shape:
// <div id="myId" class="myClass">
// <p>Some Text</p>
// <br>
// </div>
document.body.appendChild(customElement)
You certainly don't have to use it, do whatever floats your boat, but I just find that a helper function like that makes it easy to write HTML-looking Javascript code, without the temptation to actually use .innerHTML.
Just use it. It won't affect the performance.
it shouldn't effect performance. If anything, if the scripts loading is deferred it might improve the performance.
As for bad practice, I don't think it would be. I mean how is it any different to something like React that has a html file with a div with an id and injects the bundled react app (webpack js files) into

How many ajax files should I have? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm starting out php.
I'm wondering how many ajax files should I have. Should I have a seperate one for each operation I want to do? each query insert etc,
Or do I like send something in the data, or maybe request that ID's the request so that the server knows what to do?
Is there a good example for that?
I don't know if it matters but I'm using jQuery.
To answer your question, I personally like having as many files as possible (with fewer lines of code), but keeping related functions groupped in an object inside the same file.
For example, you could have one file called userAjax.js which contains the userAjax object:
var userAjax = {
getUserLevel : function (userId) {
$.get // blah, blah, or any ajax request
},
setUsername : function (userId, username) {
$.get // blah, blah, or any ajax request
}
};
In your app you could then use (after including the userAjax.js):
userAjax.setUsername(37, "John");
I like using this method because it keeps code structured, you do not have too much code for too little functionality. I use it in small to medium sized projects and works great :) (both for production & maintanance).
For the server-side, you could either do the same thing, or simply have a file for each command. I also like file-per-command method because if you structure your files in folders it's very easy to maintain the code (you can go directly to the function you want by navigating through the file tree). But again, for larger projects I think you should use a more OOP-approach, like having a class with many functions in a single file.
To sum it up, it all depends, mostly based on the size of the project.
Well, you can create functions for all operations what you want to do, and handle this functions with one file. Or you can create as many as want files for handling requests. If you are using some framework built on MVC architecture, you will probably use only one file (Controller) or more functions in more controllers, it is really variable, depending on usage.
There is lot of tutorials how to use PHP with AJAX. You just need only search for them.

Is it a good practice to use php code inside javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I heard lot of experts saying entering php code inside javascript is not a good practice. I wanted to know if it's true. If yes, then will it effect the performance? or is there any other reasons?
For example:
<?php
$num=1;
?>
<script>
var x = "<?php echo $num;?>";
</script>
No, it is not good practice.
will it effect the performance?
I do not specifically know which performance you meant when you wrote that line, but about all performances I can imagine, I would say: Most certainly, no.
is there any other reasons?
Mixing two languages is hard as it requires proper encoding. This makes things complex. Complexity is bad practice.
Typically, it is bad practice to use language X to generate code in language Y.
Try decoupling the two languages by making data their only interface -- don't mingle the code.
In your example, you could improve the code by using PHP to populate a cfg structure that's available to JavaScript:
https://softwareengineering.stackexchange.com/questions/126671/is-it-considered-bad-practice-to-have-php-in-your-javascript
NO it will not effect the performance, but it affects manageability and security.
In your case, can your javascript function without knowing the value of num? or Are you just developing the JS script from PHP? Latter is the use you should avoid.
Lets take an example where num was used to know the number of items in shopping cart. Now thats a very vital piece of information, but since its JS, it can easily be manipulated. In such case, you should store such sensitive information on the server and not on the client.
A few points:
You lose the ability to minify your JS scripts because it depends on PHP output
Code quickly gets difficult to maintain. You will need to scan through PHP tags in your javascript code.
Normally, I declare a global config object and pull it through a separate ajax request when the page loads (This can be a PHP script echoing JSON).
MyApp : {
x: '123',
y: 'xxx'
}
and then access it from my javascript files later:
(function(){
alert(MyApp.x)
})();
I dont think this a bad practice, if the values are dynamic, you can just do as,
test.php
<script type="text/javascript">
var foo = '<?php echo $foo;?>';
</script>
<script type="text/javascript" src="test.js"></script>
test.js
$(function(){
alert(foo);
});
If it is not dynamic values, recommends no need to use php tags
I don't think it is that bad. Assign your dynamic PHP values to a JavaScript variable in your PHP templates(as first line if possible) and then call these variables inside your external JavaScript files. And I fully agree with #hakre answer.

Is building big portions of page in javascript bad? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
On an existing project I am working on, I noticed many of the developers are building big portions of pages with javascript. For example:
$( targetdiv ).append("<div>");
$( targetdiv ).append(" <div class='info'>");
$( targetdiv ).append(" <div id='modes'>");
$( targetdiv ).append(" <table cellspacing='0'>");
$( targetdiv ).append(" <tbody>");
// much more...
I understand using javascript to build certain elements on page. Sometimes the content is dynamic and it is now know when the page first loads (ajax stuff).
However, most of the code (not all is shown) is not dynamic and will be build the same way every time. No 'if' statements or loops
Is there any reason why one would build large parts of pages using javascript vs just having the html be part of the html doc? I would think one would want to minimize javascript html generation because its more confusing and harder to write. Also, javascript html generation has to hurt the performance (Does it?)
I am a "newer" javascript dev so maybe I am missing something. I want to say something but I am "newer" so maybe i don't get "it"
Thanks
That is quite possible the most horrible way I have ever seen a kitten getting killed. Now, that's not just a kitten you killed: each line like this kills a thousands of kittens. And puppies.
Don't do this. It's wrong. It's bad. It's horrible. It's terrible. It's hell. It's anything but good.
On a more serious note...
The code doesn't even work as intended. See the comments on your question.
The HTML is the content, the JavaScript is the behavior. You're mixing both for absolutely no compelling reason.
Every time you call the DOM, you have time to go grab a coffee. You're calling append so many times that just seeing it hurts my eyes.
From a philosophical standpoint, I would have to say this is a bad practice. html belongs in the html and that's it.
That said there are several different ways of adding html to the page via javascript.
<div id="template">
<div class="mycontent">
<!-- stuff -->
</div>
</div>
Then
$('#target').append($('#template').html());
will give you the same results without having html code in your javascript.
But if you must (and sometimes you do) the most performant way is to create dom elements in native js and operate on them:
var template = document.createElement('div');
template.className = "mycontent";
// do more stuff to template
document.getElementById('target').appendChild(template);
The native js method while offering the best performance is hard on you as a developer. So if you wish to work with it as an html string, doing the append once would be best:
var template = "<div class='mycontent'>";
template += // add more string to build the template
template += "</div>";
$('#target').append(template);
While ajax has a performance hit, as some suggested it is also an excellent way of managing your html code, allowing you to put the template in its own file. jQuery also has a shortcut to accomplish this:
$('#target').load('/template.html');
or if you wish to operate on the template:
$.get('/template.html', function(template){
//do stuff to html
$('#target').append(template);
}, 'html');
multiple append statements are with out a doubt the worst possible way to go, of all the less than great ways to go. Personally the first option I provided is my preference, and can easily be paired with libs like http://handlebarsjs.com/
Good luck!
Well, since you're new, it's a good thing you went to confirm your suspicions before taking action. That said, I'm pretty sure this is a case of lazy coding. In fact, there are actually even shorter ways of writing the code you posted, and those shorter ways won't delay the browser immensely.
For one thing, my favored way of writing large portions of the page is with a templating system - you put flat HTML files in your web directories, or in some sort of undisplayed portion of your page, and then import them when you need them to Javascript. A number of libraries can help with this.
But for goodness' sakes, even if you're too lazy to do it that way, do NOT do this with multiple append functions. That means the browser is figuring out new HTML elements and unclosed tags on each call of the function, often rewriting its own work. At the very least, append the HTML strings together bit by bit before calling jQuery.append ONCE.
var newHtml = "<div" +
" <div class='info'>" + ...
$(targetDiv).append(newHtml);

Categories

Resources