Loading JS and CSS into HTML [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I'm very new to the HTML markup language. I have an html table (that I actually generate dynamically using echo statements from a PHP file), and I want to apply some CSS and JS to it so I can have such niceties as row+col mouseover highlighting and fixed table header for scrolling. I have a few questions,
(More of a general inquiry than a specific question) Where could I find good examples of JS or how could I achieve the desired effects that I mentioned above?
Where do I place the <script> and <link> tags to import JS and CSS files so that they take effect on my table? Up until now, I place the tags in the <head> of my HTML body. I've been messing around with various examples I've come across and tried copying the JS code into a file and then telling HTML where to look using the tags but I never seem to be able to have the CSS or JS files execute

This is a very broad question as there are many ways to do this, but I would recommend checking out examples that are somewhat industry standards nowadays such as Bootstrap. They have classes like table-hover that will do atleast your row highlighting. This is a good basis to build off of.
You will want to store the css documents in the head of the page, but your scripts can be loaded in the head of the page or the end of the body. I suspect that the reason your JS documents may not be executing as you would like is because you have code that requires DOM elements (the elements on the page) to be present for event handlers and such to execute upon. You need to wait to execute the code until the DOM elements are done rendering, or atleast those that you are needing to modify.

I know Codecademy's free courses provide decent examples and practices, but other than that I'm not sure.
Most of the time CSS will be linked in the <head> and is what you'll want to do. The most agreed upon location to link you're JS is at the bottom of the page just before the </body> tag.

With your table styles, just browse around looking for some frameworks, these look great.
Where you place your <script> tags doesn't matter, they can go in your <head> or your <body>. Your <link> tags can go in your head only though.

For the effects you seek, I'm not convinced you need JS, CSS alone should probably be able to do it in itself - although styling tables isn't something I've done in recent years.
Linking to your css and js file can be done from the <head>.
If you have trouble getting it to succeed:
"inspect" your page in your browser (depends on the browser how to start it)
look for errors both on the server and/or the console of the browser
I'd expect something to be wrong with the path: if it's a relative path (not starting with http(s):// nor with "/"): it's relative to the path the html is on. If it's an absolute path well then that's from the doc root in the server.

Related

Is it a good practice to load HTML via Javascript and PHP? [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 3 years ago.
Improve this question
I am planning to make a website which has completely different header on mobile and Web as it could not be acheived using media queries. So I was planning to use javascript and php to load the header as per the size of the screen using php include.
The code for the following is as follows
//Javascript
let header = document.getElementById('headers');
if(window.innerWidth >= 800){
header.innerHTML =`<?php require_once "./assets/inc/header-web.php" ?>`;
}else{
header.innerHTML =`<?php require_once "./assets/inc/header-mobile.php" ?>`;
}
//Markup
<div id="headers"></div>
I have made two different types of headers and saved it using the names header-web.php and header-mobile.php.
Now I want to know:
Is this a good practice to follow or will it cause any issue or bug in my website?
Whether this will be a burden on my DOM and will affect my page load?
Will it use too much of resources as two files are loaded every time a page is loaded?
Is there any other way to achieve it?
Is this a good practice to follow or will it cause any issue or bug in my website?
It will not cause any issues for you in a sense that this code will work. However, I wouldn't be glad to see such code during a code review because it violates separation of concern. Right now you have backend and frontend code mixed together which turns the code into spaghetti. You will have a hard time debugging your website. A better solution would be to put all the layout logic to Javascript. For instance, having two divs and using JavaScript to show/hide one of them, or putting two text into javascript variables and just using one that fits current width.
Then you could separate backend-code by reading files in a controller class (if you follow MVC) or at the start of your HTML. Something like $mobileHeader = require(...). In your template: <div id="mobileHeader" style="display: none"><?=$mobileHeader?>>.
Whether this will be a burden on my DOM and will affect my page load?
No, PHP happens on server-side so the browser wouldn't know the difference.
Will it use too much of resources as two files are loaded every time a page is loaded?
No, it's fine resource-wise. You'll have to read those 2 files anyway, but HTML markup is just not the best place to do it.
Is there any other way to achieve it?
I've answered that as a part of question #1.
Conclusion
To sum it up, you did a nice piece of code that works fine and is actually quite succinct. You could also improve your code habits by separating logic and representation.
So, I think that wether or not is a good practice depends on your personal style. I see people doing it this way many times, and others doing it in very different ways. There's always a new solution for these sort of things.
That said, this way of doing it will actually slow page load, becouse when you are doing <?php require_once "./assets/inc/header-mobile.php" ?> you are essentially evaluating a script and inserting into the html the evaluated value. Obviously that depends on how big are your files though.
One other way of achiving this would be to detect the screen width on page load, and then swapping out a template header with one that you download with an ajax (or similar) call, for example.
<div id='header'>loading animation?</div>
document.addEventListener("load", () => {
if (window.innerWidth >= 800) {
fetch(url).then(response =>
/* swap header */
)
} else {
fetch(otherurl).then(response =>
/* swap header */
)
}
});
Example with ES6 using fetch API.
1.Whether this will be a burden on my DOM and will affect my page load?
Yes, definitely it will increase the page load time.
2.Will it use too much of resources as two files are loaded every time a page is loaded?
No, it will not load two files resources. If it is mobile, it loads mobile header, and its all resource files. If it is web, it loads web header, and its all resource files.

Single Page HTML Site - SEO technique [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I developed a Single Page Responsive Website for my company http://germin8.com/ . Everything is going good however I actually now face a problem with SEO .The site's different sections do not show up in search engine.
I know the cause it being a single page site so not crawler friendly...Inorder to get the URL change I used history pushstate technique and have put href links for menu bar items to sections ..... confused ?? eh
Sample anchor tag outlink ( I thought this is enough for my section to show up in Search Engine :-/ )
a style="text-decoration:none;color:black;padding-left:30px;" class="scrollTo" id="contactUs_Menu"
href="/contact-us">CONTACT</a></li>
Or you may have a look at the source code of the website and follow the anchor tags.
On some research and POC I came across this AJAX crawlable technique by google (https://developers.google.com/webmasters/ajax-crawling ) ...however I couldn't understand it and also feel loading site's sections through ajax would be a lot more work at this stage since my entire site is a static HTML file ( index.php ) with nothing rendered dynamically through javascript/AJAX
Someone who has faced similar problem can you suggest me the simplest and fastest way for my site's different sections ( eg .Clients , Partners , Contact Us etc ) to show up in google engine
Thanks in advance guys :)
Actually this question is more suitable for https://webmasters.stackexchange.com/ but since it has been raised here, I'll try and answer this question to the best of my knowledge.
Unfortunately, there is no shortcut for SEO and to be able to fetch search results in your favor is a slow and painful process. The basic principle of SEO is doing simple things right and provide quality content to your users in your website and not worry much about the ranking.
That being said, your expectation is slightly unrealistic for the following reasons,
You are asking Google to index a page that doesn't even exist.
The URL is changed with JavaScript on runtime, which is something no-search-enginebot is good at indexing.
However, there are couple of things that you can improve in terms of SEO (not going to guarantee what you have asked),
Make sure you have sitemap.xml file in the root directory of your website. You need to add individual sub-page links for each url like this,
<url>
<loc>http://germin8.com/clients</loc>
<lastmod>2005-01-01</lastmod>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
Once you are done with sitemap.xml file. Open your Google Webmaster Account (also make sure your Google Analytics account is linked to your webmaster profile) and validate the structure and schema of the sitemap file.
Write better anchor text - Add title attribute to your anchor tags. Avoid inline styles as much as you can. Use complete url instead of relative paths for href attribute.
Google doesn't like slow websites. Hence, you need to focus a lot on the performance of your website. Also no user likes to see a webpage loading for ages. Make efforts to concatenate, minify and lint your assets(html/css/js). Gzip compression is required as well.
149 requests with 4.1 MB is huge. You need to reduce the number of HTTP requests you make massively!
Conclusion
Apart from the above, I don't really see your internal links not being visible on search results as a big problem. Your primary objective is to make sure that your users land on your webpage (this is something that you already doing). After the user enters your territory (website) he has the liberty to navigate to any section of the webpage.
http://webcache.googleusercontent.com/search?q=cache:http://germin8.com&client=firefox-a&rls=org.mozilla:en-US:official&strip=1
I dont see any problem with indexing of your site. Clients will not showup in normal search but they would show up in google images. You should give alt tag to best describe the client images that you have used. Above url will give you an idea how Google bot sees your site. So you can notice all text is indexed by google including your heading where clients are listed. Hope this solves your concern.

Mobile website too slow on the phone [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 am building a prototype for a mobile section of a website. It uses no dynamic staff, just jQuery and Foundation 4. When I test the site in the iphone's browser, it's very very slow to load and to respond to touches. Can some experienced folks please tell me all things to make sure the site loads and operates faster on the mobile device?
All my images are saved "for web", so they shouldn't be a problem. Could it be slow because my CSS style sheet is very lengthy? I am not an expert at combining and applying one classes to a lot of things yet, so may be I have too many id-s and separate classes? Would that be a big deal in this case though? Also, could it be slow because I am using Foundation, jQuery and a Flexlider plug in and each of them has their own multiple style sheets and .js files? Should I throw away any files I am not using from their folders? Am I on the right track and what else can I do? Thank you in advance.
There are some things which helped me to make my mobile app more faster. I had the same issue as you, the screen response was very low.
Get rid of every unused code
I had a lot of commented code and files that i actually didn't use. This includes css styles that aren't used.
Do you even need classes or Ids?
Looking at my app, i had almost on any element a class or Id. Were i instead could use a element selector. here some more info about the selectors. Follow the DOM structure. I mostly used a class for groups and Ids for one specific element(which i almost never needed).
Check if you have css styles that doesn't add something
Sometimes you have multiple styles that doesn't actually add anything to it. A great example is using a float: *; and display: inline-block;. When using both of these on one element has no extra function as float makes the element inline-block by default.
optimize you script
With this i mean, see if you can shorter you codes with the same functionality. Using two almost identical functions? short them to one function. Also using premade function of your script language will really help you to make your code faster. So don't create your own sort function, but use the premade function.
For help on optimizing you code, i suggest you to take a look here.
jQuery selectors
Make your jQuery selectors more specific. For example:
You may have a div with class content.
<div class="content"></div>
Instead of selecting it with
$('.content')
You could use
$('div.content' )
jQuery can now restrict the search to DIV elements only.
More info fore more efficient jQuery selectors here
Store determenation code
When you get information, for example screenWidth minus the width of a other div, and you using this more then once, store it! This way your webpage hasn't to do the calculate over and over and can just get the variable.
Don't use 'big' plugins when using half of it
When you only use a small part of a plugin you're using, it's better to find or a other plugin or code it yourself. Loading the plugin files might harm your performence, would be a shame if it actually wasn't even necessary.
This is just a global view were I had a big advantage on and I hope you can find a fine use for this.
Feel free to correct me when I'm wrong.

SEO : Move content with javascript? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I placed a text early in the html code for SEO reasons, but visually, this text should be at the bottom of the page. I can't do this with just CSS.
My question: is it a problem for SEO if I move the text in the DOM with javascript? Not hidden or removed, juste moved.
Thanks !
If you placed your text in the beginning for SEO reasons, but moved it down because it isn't aimed at the user, Google will interpret that as misleading to the end-user. If they'll notice a single paragraph? Doubtful. But if you were to make this common practice, I believe this would go in the category of Blackhat SEO, even though it's mild in comparison to other things you can do.
You have to remember that visitors that end up on your site through Google, is a customer of Google. And if the user thinks he/she was mislead, it falls on Google not doing a good enough job. Keep that in mind when designing.
A tip, if you're looking for one, is to simply never do things like this. If you design your site and script your text well enough that the visitor finds it useful, Google will see that and ranking will follow. This has been my experience anyways - shortcuts have never worked out (for me) in the long run.
Any "I want machine to see content more prominently, but obscure it from user" action is simply called cloaking and will reflect negatively on your index once caught.
How much will it take? Depends on many factors, including complains from users lured to your site if it indeed have nothing but "SEO reasons" to it.
The most important content first is good SEO practice.
You cannot say that moving content around is bad SEO practice per se. Take a look at the HTML of wikipedia for example. The content of a detail page (the article) within the HTML is before the HTML of the navigation, for example.
The bot will see it more prominently, it's the most important thing on the page and that's it.
Another example: Why should it be bad practive to place content first in the HTML and "move up" a slider with some images, completely coded in JS? Things like that.
In one video on YT Matt Cutts discusses a similar question with Javascript and dialog elements that toggle the display of texts (show/hide) which is quite common. As long as typical phrases are used (on, off, more, see more, things like that) and you use common tools you don't look suspicious.
As usual, the devil will be in the details.

Is there a JS diff library against htmlstring just like google-diff-match-patch on plain text? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 months ago.
Improve this question
Currently I am using google-diff-match-patch to implement a real-time editing tool, which can synchronize texts between multiple users. Everything works great when operations are only plain texts, each user's operation(add/delete texts) could be diff-ed out by comparing to old text snapshot with the helper of google-diff. But when rich format texts(like bold/italic) are involved, google-diff not working well when comparing the htmlstring. The occurrence of character of < and > messed up the diff results, especially when bold/italic format are embedded within each other.
Could anyone suggest a similar library like google-diff to diff htmlstrings? Or any suggestions can get my problem fixed with google-diff? I understood google-diff is designed for plain text, but really didn't find a better library than it so far, so it also works if a doable enhancement to google-diff can help.
The wiki at the google-diff-match-patch project shares some ideas. From
http://code.google.com/p/google-diff-match-patch/wiki/Plaintext :
One method is to strip the tags from the HTML using a simple regex or node-walker. Then diff the HTML content against the text content. Don't perform any diff cleanups. This diff enables one to map character positions from one version to the other (see the diff_xIndex function). After this, one can apply all the patches one wants against the plain text, then safely map the changes back to the HTML. The catch with this technique is that although text may be freely edited, HTML tags are immutable.
Another method is to walk the HTML and replace every opening and closing tag with a Unicode character. Check the Unicode spec for a range that is not in use. During the process, create a hash table of Unicode characters to the original tags. The result is a block of text which can be patched without fear of inserting text inside a tag or breaking the syntax of a tag. One just has to be careful when reconverting the content back to HTML that no closing tags are lost.
I have a hunch that the 2nd idea, map-HTML-tags-to-Unicode-placeholders, might work better than one would otherwise guess... especially if your HTML tags are from some reduced set, and if you can perform a little open/close touchup when displaying interleaved (strikethrough/underlined) diff markup.
Another method that might work with simple styling would be remove the HTML tags, but remember the character-indexes affected. For example, "positions 8-15 are bolded". Then, perform a plaintext diff. Finally, using the diff_xIndex position-mapping idea from the wiki's first method, intelligently re-insert HTML tags to reapply stylings to the ranges surviving/added. (That is, if old positions 8-13 survived, but moved to 20-25, insert the B tags around there.)
jsdifflib - A Javascript Visual Diff Tool & Library
https://github.com/cemerick/jsdifflib
There's a demo here: http://cemerick.github.io/jsdifflib/demo.html
Pretty Diff does everything you need, except you will need to update the DOM response so that the diff fires against the "onkeyup" event instead on button click.
http://prettydiff.com/
Take a look at SynchroEdit, might be useful.
There is another popular library called JSDiff https://github.com/kpdecker/jsdiff. It works with HTML content too. The only drawback is that it requires a new line carriage return at the end of each line to treat it as a different line. Otherwise, all the HTML content will be treated like a single line.

Categories