0

What behaviour should be preferred for widget initialization:

1) Required HTML is generated by widget itself:

Layout:

<div id="my-widget"/>

Initialization:

$('#my-widget').myWidget(); // Creates HTML

2) Required HTML is placed to the page by user:

<div id="my-widget">
 <div class="foo"/>
 <div class="bar"/>
</div>

Initialization:

$('#my-widget').myWidget(); // Won't create nested div's

Mark Otto (one of Bootstrap creators) suggest not to generate markup by javascript: https://github.com/mdo/code-guide#javascript-generated-markup

Currently, I use the following function, which appends element to the root of the widget (this.$element) only if it doesn't exist:

function($content) {
 var $child = this.$element.children('.' + $content.attr('class'));
 return $child.length ? $child : $content.appendTo(this.$element);
};
asked Dec 9, 2013 at 17:39

1 Answer 1

0

I think it depends on how you will use the widget.

  • Generate all html by javascript if the widget is not related to the page. Having javascript handle all makes your widget self-contained and it can be easily integrated.

  • Write your html out and add the behavior with javascript, if your widget is part of your page.

I don't think that there is a reason to refrain from creating html in javascript. It is a design choice you have to take. Either you take javascript as the base or html.

The classic approach is to take html as base, but you could also create everything with javascript. That's what you do when using a framework like ExtJs : the html file would typically have an empty body.

On the other hand I agree fully with the argument stated in the html coding guide you link:

JavaScript generated markup

Writing markup in a javascript file makes the content harder to find, harder to edit, and less performant. Don't do it.

answered Dec 9, 2013 at 18:27

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.