What is the best way to create a JS integration file?

advertisements

I have blocks of HTML & JS and want to compile it all in to one JS file so I can use a one line embed on external client sites. Like <script src="http://example.com/assets/js/myembed.min.js"></script>

Sample Code

<div class="page-container">
    <div class="container">
        <br />
        <button class="btn launchConfirm">Launch Confirm</button>
    </div>
</div>

<div id="confirm" class="modal hide fade">
  <div class="modal-body">
    Do you want to continue?
  </div>
  <div class="modal-footer">
    <button type="button" data-dismiss="modal" class="btn btn-primary" data-value="1">Continue</button>
    <button type="button" data-dismiss="modal" class="btn" data-value="0">Cancel</button>
  </div>
</div>
<script>
$('.launchConfirm').on('click', function (e) {
    $('#confirm')
    .modal({ backdrop: 'static', keyboard: false })
    .one('click', '[data-value]', function (e) {
        if($(this).data('value')) {
            alert('confirmed');
        } else {
            alert('canceled');
        }
    });
});
</script>

Should I wrap it all in document.write or is the a better method to achieve this? And if this is the best way, what is the best way to do this automatically, I.e. Using Grunt/Gulp?

E.g.

document.write("<div class=\"page-container\">");
document.write("        <div class=\"container\">");
document.write("            <br \/>");
document.write("            <button class=\"btn launchConfirm\">Launch Confirm<\/button>");
document.write("        <\/div>");
document.write("<\/div>");

Thanks in advance.


Do not use document.write.

var x = '<div> All your html code store in variable </div>';
$("#InsertHere").html(x); // insert where you want

or document.getElementById("InsertHere").innerHTML = x;

// continue your actual code once those elements are ready
$('.launchConfirm').on('click', function (e) { }

It is quite not possible to embbed html code without using DOM insertion methods which always requires selector. You could create a unique class name and the tag that has that class name will be inserting this code. This is what jQuery does too.

<div class=".innerHTML"></div> // you have to ask them to create such element