How to use SyntaxHighlighter in sharepoint 2013 blog (Office365)?
I am trying to enable code highlighting with SyntaxHighlighter on a sharepoint 2013 blog site (office365 portal).
Here is the code I put at the beginning of the main page (the js and css ressources are loaded before):
<script type="text/javascript">
function sh(){
SyntaxHighlighter.highlight();
};
// executed when SP load completes
_spBodyOnLoadFunctionNames.push("sh");
</script>
_spBodyOnLoadFunctionNames should provide a mechanism to trigger functions after a page load event, but it never seems to have executed. Running my sh function from development tool (console) works as expected.
Anyone have a clue, am I using the correct event?
source to share
+ Vadim Gremyachev's answer is valid with IE but doesn't work with chrome, here is the workaround I used (inspired by fooobar.com/questions/149504 / ... ):
function sh(){
SyntaxHighlighter.highlight();
};
function setIntervalX(callback, delay, repetitions) {
var x = 0;
var intervalID = window.setInterval(function () {
callback();
if (++x === repetitions) {
window.clearInterval(intervalID);
}
}, delay);
}
$(document).ready(function () {
if( $('.syntaxhighlighter').length == 0 ){
setIntervalX(function() { sh() }, 1000,5);
}
$("a").on("click",function () {
if( $('.syntaxhighlighter').length == 0 ){
setIntervalX(function() {
sh()
}, 1000,5);
}
return true;
});
});
source to share
_spBodyOnLoadFunctionNames
array declared in init.js
(it is part of the SharePoint JavaScript library)
According to init.js
:
AttachEvent("DOMContentLoaded", _spBodyOnLoadWrapper, document);
window.onload = _spBodyOnLoadWrapper;
Where
function _spBodyOnLoadWrapper() {
ExecuteOrDelayUntilScriptLoaded(ProcessDefaultOnLoad, "core.js");
//the remaining code is omitted for clarity..
}
function ProcessDefaultOnLoad() {
ProcessOnLoadFunctionNames(_spBodyOnLoadFunctionNames);
//the remaining code is omitted for clarity..
}
function ProcessOnLoadFunctionNames(onLoadFunctionNames) {
if (onLoadFunctionNames != null) {
for (var i = 0; i < onLoadFunctionNames.length; i++) {
var expr = "if(typeof(" + onLoadFunctionNames[i] + ")=='function'){" + onLoadFunctionNames[i] + "();}";
eval(expr);
}
onLoadFunctionNames = [];
}
}
To summarize, the above approach is the correct mechanism for triggering functions after a page load event.
Actually it works just fine for me (see picture below)
Make sure the library is init.js
loaded before initialization _spBodyOnLoadFunctionNames
.
Alternatively, you can try the following approach:
<script type="text/javascript">
function sh(){
SyntaxHighlighter.highlight();
};
ExecuteOrDelayUntilScriptLoaded(sh, "core.js");
</script>
results
source to share