Forums

Cannot load jQuery with Flask

Hello all,

I'm beginner in javascript and I'm struggling loading jquery with Flask.

I know it should be placed in the static folder but jQuery is not detected.

I've found a small script to check whether jQuery is loaded or not (see after).

Could you please help?

{% block content %}

<script src="js/jquery.min.js"></script>

<script>
window.onload = function() {
if (window.jQuery) {
    // jQuery is loaded
    alert("Yeah!");
} else {
    // jQuery is not loaded
    alert("Doesn't Work");
}
}


</script>

Many thanks in advance,

Nicolas

It's very unlikely that the path you're using for jquery is correct. That's a path that is relative to the url of the current page.

If you have your javascript in a static directory for /js, then the src should start with /js, not js. If you have a static file mapping for some other path to your javascript files, then it should start with that.

Thanks a lot for the answer Glenn,

Unfortunately, it isn't working.

I've even tried full path: <script src="/home/t3302/mysite/static/js/jquery.min.js"></script>

without good result..

any other idea?

That's not a URL path, it's a file path. Your URLs must refer to the place where the web server is serving the file, not where the file happens to be on disk.

Maybe the docs on static file mappings will help you.

Actually, the url_for should be specified:

<script src="{{ url_for('static', filename='js/jquery.min.js') }}"></script>

And now it's working :)