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);
};
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.