Search code examples
javascriptsyntaxhighlighter

How to load Syntax Highlighter on pages which contains pre tag ?


i am a Blogger and sometime's i need to demonstrate codes on my blog, so i used a Syntax Highlighter by Alex Gorbatchev. But the problem is that the files loads in each and every page of my Blog and that makes the blog load slow.

I have got codes on some pages only so i want a way to load the SyntaxHighlighter files only on pages having tag. If there is any way to do it please help me out.

I searched StackOverflow for this question but didn't found any thread which can answer me.


Solution

  • If you're using jQuery and requirejs already, you could do something like:

    var preElements = $('.pre');
    if (preElements.length > 0)
    {
        //load the JS
        require(['shCore.js', 'shBrushJScript.js'], function (){
          //now apply it
          SyntaxHighlighter.all()
        });
    }
    

    Be careful that your logic doesn't somehow double apply to the same s.