Bootstrap's JavaScript requires jQuery While jQuery is already loaded
<p>I'm facing an error with loading the <code>Bootstrap</code> library as it always gives this error:</p>

<blockquote>
  <p>Uncaught Error: Bootstrap's JavaScript requires jQuery</p>
</blockquote>

<p>Despite that I'm attaching the <code>Bootstrap</code> library after making sure the <code>jQuery</code> is loaded but still getting the error.</p>

<p>I'm using the following code to attach the <code>jQuery</code> to the page by creating the element and append it to the <code>document</code>:</p>

<pre><code>/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '3.1.1') {
    console.log("jQuery LOADED");
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type", "text/javascript");
    script_tag.setAttribute("src",
        "http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js");


    // Try to find the head, otherwise default to the documentElement
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);


    if (script_tag.readyState) {
        script_tag.onreadystatechange = function () { // For old versions of IE
            if (this.readyState == 'complete' || this.readyState == 'loaded') {
                console.log(window.jQuery.fn.jquery);
                scriptLoadHandler();
            }
        };
    } else {
        console.log("ONLOAD STATE");
        script_tag.onload = scriptLoadHandler;
    }
} else {
    // The jQuery version on the window is the one we want to use
    jQuery = window.jQuery;
    main();
}

function scriptLoadHandler() {
    // Restore $ and window.jQuery to their previous values and store the
    // new jQuery in our local jQuery variable
    jQuery = window.jQuery.noConflict(true);
    // Call our main function
    main();
}
</code></pre>

<p>Here I'm creating the <code>Bootstrap</code> after <code>document</code> is being ready:</p>

<pre><code>function main() {

    jQuery(document).ready(function ($) {
    var bootstrap_script = document.createElement('script');
    bootstrap_script.setAttribute("type", "text/javascript");
    bootstrap_script.setAttribute("src",
    "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js");

    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(bootstrap_script);
    })
}
</code></pre>

<p>Just to clarify a critical thing
I'm writing the <code>js</code> code in a separated <code>js</code> file, because I want to use later as a <code>jQuery plugin</code>. Thus, I'm trying to attach the libraries as I don't guarantee that the targeted page would include those libraries or not</p>