Skip to main content
Inspiring
October 28, 2015
Question

What's the best way to add large html chunk (like a form and html etc.) using javascript?

  • October 28, 2015
  • 1 reply
  • 841 views

Hi all,

In php - we can do and if statement something like:

<?php if ($test1 !=''){

?>


add HTML HERE


<?php

// end if here

} ?>

and the html will only show if the condition is met.

Q: So, What's the best way to add large html chunk like a form using javascript IF statement or  a better way???

like this - or...???

<script>

if ( test1 !="" ){


//this....

document.getElementById('showthis').innerHTML = "large html chunk";

}


// or this....

$.get("codeblock-1.html", function(fileData){

$('put-stuff-here').html(fileData);

});

// or something better?

</script>

This topic has been closed for replies.

1 reply

revdaveAuthor
Inspiring
October 30, 2015

Hi all,


Someone mentioned using CSS hide which worked well but ultimately I found this:

http://api.jquery.com/hide/

And it really did the trick.... (& TREAT)!!!

David_Powers
Inspiring
November 1, 2015

Using that is fine for hiding a form, but be careful about using it for elements that contain images. The jQuery hide() method sets the CSS display property to none, but all the content will still be downloaded.

sinious
Legend
November 9, 2015

I agree with David, I think you're better off making the conditional check first and actually loading the HTML after that.

I don't presume you're getting extremely deep into JavaScript content generation if you're dumping a lot of string data into the DOM but for the record, the DOM Fragment is a lean machine for generating any verbose content via JavaScript. Using it would even allow you to half the loading of images before they're needed. In short terms, every time you do "anything" to the DOM (like add content, any kind), the whole thing needs to reflow to take your changes into consideration. DOM Fragments can be created entirely on the side and do not cause this to happen, UNTIL you're done generating your DOM and you append it to the document.

It's may be a bit more of an advanced topic than you need but here's more info about performance and examples:

Document.createDocumentFragment() - Web APIs | MDN