Importing stylesheet and Javascript
It is normal for FE developer to import CSS, Javascript library code somewhere over internet and use it. It’s convenient but we will also face some issues with it. I will explain about it in this post.
First, we will take a look into an example. Let’s see how can I import CSS and javascript library. I will use Bootstrap (an UI library) and JQuery (a Javascript library).
As you can see I didn’t write any CSS properties. Styles of class name “btn btn-primary” are applied when your browser finishes downloading and parsing Bootstrap CSS file.
Next, I will try to custom Bootstrap and use JQuery.
CSS code worked as I expected but JQuery code didn’t work. Then I tried to move JQuery to bottom and it worked.
The explanation for this is when the code executes, the button hasn’t appeared in the document yet. Normally, You want all elements to be available before executing javascript code. So, I can use JQuery document ready function and place it on top without problem.
$(document).ready(function(){
$(“#primary_btn”).text(“dynamic primary button”);
});
It is easy to import CSS and javascript in tranditional way. But with framework, it will be difficult to add dynamic script.
Let’s say you are using React framework and your customer wants to add a chat script bases on client_id. You added the script to bottom of your component but it didn’t work.
<script src=”https://dummydomain.com/chat.js?client_id={client_id}"></script>
The reason is the native of React itself. innerHTML API doesn’t support script tag. I also agree with this for security reason. The workaround for this is adding script tag manually using document object.
To be noticed that it is not guarantee that your scripts are executed in order using above workaround.
script1.js
script2_depends_on_script1.js
So, it is important that you understand how your code and library work.