Insert a lot of HTML and a stylesheet into page with jQuery - Best practice?
I've made a开发者_运维问答 website theme and I've included a bar that sticks to the side of the screen and offers various settings. However, It requires a fair bit of markup inside the page and part of my themes selling point is it's clean/minimal source code!
So I would like to include my bar by just using one line of JavaScript. Is there a way to use jQuery to insert the HTML code and the stylesheet? Also does this go against best practices and am I likely to be penalized (by google) for doing it this way?
EDIT: I've edited the questiont to make it clear I'm not asking for a jQuery stylesheet switcher (thanks).
Robots do not execute javascript. Robots do not see any content generated by javascript.
So if you are going to generate the menu with JS, that is what will happen.
And to answer the question "Is there a way to use jQuery to insert the HTML code and the stylesheet?" Yes there is.
Just use for example plain .append() for both. For stylesheet $('head').append() and for the other you put it where you like it to be, maybe $('body').append() ?
I'm not sure if this isn't the case any more, but if I recall correctly, search engine robots don't run javascript, but that might have changed.
Performance wise, wrapping a big string of html with $() is better than a better looking markup where you create a base element, insert the children, then proceed to insert their children, etc.
As for best practices, the method if inserting one big slab of HTML is often not that easy to maintain, unless you're using some sort of template file for the HTML. If it's just a big string in a JS file you won't have any syntax highlighting and correct HTML behaviour in the editor. So if performance is not an issue (For example if it's not that much HTML and it's only inserted once), I'd go with the more structured approach, for maintainability.
This could be an appropriate time to start using LESS: LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions. (Using this you can avoid making large number of stylesheets)
Also you can have a look at how jQuery UI team made their theme roller which is light and easy using @import statements.
Also jQuery style switcher is a very small plugin which I like the implementation of.
If i understand you correctly, you can do something like this example:
http://jsfiddle.net/ajthomascouk/DbRwn/
In this example it just changes the text colour. However you could use this method to change the src of your style sheet (see UPDATE).
UPDATE Like this - http://jsfiddle.net/ajthomascouk/DbRwn/2/
Hope this helps.
精彩评论