2

I have a simple script that I placed inside it's own file (my_file.js). This script depends on jQuery. Obviously users can access its functionality via the script tags inside the head tags:

<head>
<script src='http://code.jquery.com/jquery-3.3.1.min.js'></script>
<script src='my_file.js'></script>
</head>

This works perfectly, since the JS is loaded sequentially. But I would like users to not have to add jQuery explicitly at the top. Is there a way my_file.js can itself load jQuery prior to its own JS, such that users only add the one file:

<head>
<script src='my_file.js'></script>
</head>

I know modules and bundlers take care of this issue, but I'm interested to see if there is an approach that allows one file to bring in its dependency, and wait until it's loaded before running the rest of the script.

Is there something like dynamic imports, such that:

import('http://code.jquery.com/jquery-3.3.1.min.js').then(module => {
  // load my scripts here
});

Or AJAX in vanilla JS:

var xhr = new XMLHttpRequest()
xhr.open('GET', 'http://code.jquery.com/jquery-3.3.1.min.js')
xhr.onload = function() {
    if (xhr.status === 200) {
        // load my scripts here
    }
    else {
        console.log('Request failed.  Returned status of ' + xhr.status)
    }

}

Everything I try runs my_file.js before jQuery. How can I make sure jQuery is loaded first, without having to place it in the tags?

0

1 Answer 1

1

Open jquery.min.js on your browser. Select all code and then copy it. Then paste it to the beginning of my_file.js.

The code should like:

/*! jQuery v3.3.1 | (c) JS Foundation and other contributors | jquery.org/license */
!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){"use st.....

// Your code here...
Sign up to request clarification or add additional context in comments.

11 Comments

What if it already exists and version you include is not compatible with version already existing?
@charlietfl jquery will not be initialized if its already initialized.
That is not true. When you load multiple versions they each overwrite the global object unless using noConflict()
@MisirJafarov I actually tried this first, but I get SyntaxError: Unexpected keyword 'function' .... which occurs after the first function of my own code.
@Cybernetic not doing things right then
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.