I’ve been adding JavaScript code many times in my earlier blog posts. I know I struggled to do that. But I was too stubborn to google for clues because somehow what I did is working *GRIN*
Anyway, recently I struggled again, but this time I don’t have the energy to be stubborn, I googled for solution.
According to this article, this is the best way to incorporate JavaScript into WordPress blog post:
- Save your JavaScript code in a .js file
- Use SCRIPT tag to load the .js file
- Add another SCRIPT tag to execute any initiation functions
It will be something like this
<script type="text/javascript" src="/scripts/myscript.js"></script> <script type="text/javascript"> <!-- Initialize(); // With assumption that this function is defined inside myscript.js --> </script>
That’s all, very simple and straighforward indeed. So now looking back, what’s wrong with my earlier method anyway? Chronologically speaking, it would be as follows:
- I put the code directly inside a SCRIPT tag
- Then I realized that WordPress added <br/> to replace the newline, which basically prevent my JavaScript code running
- I removed the newline from my JavaScript code
Which is really horrible, considering that:
- my code is now unreadable to human 😀
- I must tirelessly replace all single line comments (// …. ) into multiple line style ( /* …. */ )
- It makes debugging with Firebug really difficult
Hmmpffhh… I learned my lesson, so let’s move on 😉 Did you ever make similar mistake because of your stubbornness?