I'm trying to prettify my code in Blogger. I've linked Google JS and CSS files to my template. The problem is that I want the code to be prettified on page load, so I add prettyPrint();
to page load event on the template.
<body onload="prettyPrint();">
This code doesn't get executed. However, if I type prettyPrint() manually in the console, my codes get prettified correctly. Does blogger template block invoking JS functions manually?
EDIT I get it to work by manually invoking the function in every post that I needs code prettifying (see below). Still, I want to know why I can't do it on the template.
<pre class="prettyprint linenums lang-js">
function testCode(){
}
</pre>
// I have to do this in every post :-s
<script type="text/javascript">
prettyPrint();
</script>
EDIT 2 The README said that I shouldn't use prettyPrint()
directly as a handler but wrap it in a closure instead. So I added this code, similar to the example in the README, in my <head>
but to no avail.
<script type='text/javascript'>
window.addEventListener('load', function (event) { prettyPrint() }, false);
</script>
OR
<script type='text/javascript'>
document.addEventListener('DOMContentLoaded',function() {
prettyPrint();
});
</script>
EDIT 3 My template HTML is just the default Dynamics View (Classic) Template with the prettify library added as explained above.
EDIT 4 Here is a link to demonstrate the problem: http://testprettyprint.blogspot.com/2013/02/blog-post.html -- the code block is not prettified automatically but if you open Chrome's console and type prettyPrint() the codes will be correctly highlighted.
EDIT 5 The reason why I think it's my problem not blogger's because this guy still has his code prettified using the same technique: http://errorbuster.blogspot.com/2012/07/prettify-syntax-highlighter-for-blogger.html
EDIT 6 As Jeffery To has pointed in his answer, the Dynamics View loads blog content with AJAX, so any JS call on document load will get executed BEFORE the actual content is loaded. Therefore, any JavaScript performed on the actual blog content, not the document, is invalid. So I guess the question now is how to hook into Dynamics View ajax:complete
event, if there is such a thing, but I doubt there is. Thanks everyone who has replied. I'm not sure if this can be counted as a bug, but I'll file an issue with blogger.
CONCLUSION Please read Jeffery To's answer. He found the event to invoke the function.
See Question&Answers more detail:
os