Set favicons with JavaScript

In a super easy and simple way for JavaScript newbies

Spemer's favicon

When you publishing some websites, you’ll need to set favicon for the websites. If you have bunch of HTML files to do that, one tiny change might results lots of bothersome works. In this article, I’m gonna let you know how to set favicon — include shortcut icons for Android and iOS — with just few lines of code in JavaScript without fixing your HTML codes one by one.

Basic way to set favicon in HTML

We’ll make this plain HTML code runs with JavaScript, inside <head> tag. It’s pretty simple if you want to set only one kind of favicon, just for web browsers, not mobile shortcut icons or Apple touch icons.

In JavaScript

Now you’ve completed to set your website’s favicon, without writing code for every HTML files you have! You can apply this way to set favicons for other favicons or shortcut icons with JavaScript arrays.

Add array for favicons

And, we’re gonna use this array with for loop to apply it to our code above.

That’s it! In the same way, we can set other favicons like Android shortcut icons or Apple touch icons for iPhone and iPad.

Set another array and function

With the code above, we’ve completed to set touch icons for iOS.

My .js code
The way I’ve applied my favicons for my website

What’s next?

In the same way, we can also set favicons for Android shortcut icons with JavaScript, not like HTML codes below.

Now we can apply it in our JavaScript code. We don’t need to worry even if there’re small changes for favicons, which make us to fix every HTML codes for them. Just fix one or two lines in JavaScript can apply it on every websites.

Moreover, by applying dynamic parameter for the function, you can make your favicon dynamically(e.g., badge on favicon).

You can check my JavaScript code on my GitHub, or watch my live website coded with above codes. Hope you enjoyed and thank you for reading my article!

Title : Set favicons with JavaScript
Date : January 3, 2018
Writer : Hyouk Seo (Spemer)