简体   繁体   中英

Appending <head> with jQuery - doesn't seem to work?

I'm attempting to create a main js controller that includes all needed js files for my application to keep everything as structured as possible.

I thought this would work, but it doesn't seem to append anything to head :

HTML:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="../static/css/main.css" />
<link rel="stylesheet" type="text/css" href="../static/css/sub/navbar.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="../static/js/includes.js"></script>
<title>Untitled Document</title>
</head>

As you can see includes.js is imported after jQuery from Google's CDN

Contents of includes.js:

var scripts = ['../static/js/functions/notifications.js', '../static/js/functions/subnavbar.js'];
$(document).ready( function() {
    var iterate = scripts.length;
    for(i = 0; i < iterate; i++) {
        $('head').append('<script type="text/javascript" src="' + scripts[i] + '"></script>');
    }
});

I have no idea why it's not appending the contents of the array scripts to head . I tested out the script by appending the contents to body ( see this jsFiddle ).

Any answers as to why it's not working, or edits to make it work would be greatly appreciated :)!

Something to consider: this problem has been solved for you already, and an awesome JavaScript library already exists. It's called Require JS .

I strongly recommend checking it out to see if it'll work for your requirements before rolling your own dependency loader.

You are using jQuery, why not using $.getScript? This works fine in this example: http://jsfiddle.net/x6rCr/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM