0

I want append script in head if there is tag <script> in the body, i try as following but it don't work, How can done it?

DEMO: http://jsfiddle.net/rYXJx/

JS:

var TAREA = $('body').find('textarea').length;

if(TAREA > 0){ 
    $('head').append('<script type="text/javascript" src="files/js/nicEdit.js"></script><script type="text/javascript">bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });</script>');
    };
Salman A
  • 262,204
  • 82
  • 430
  • 521
Taylor Gomez
  • 320
  • 1
  • 5
  • 22
  • I don't see how your demo could work. What is nicEditors? – Christophe Dec 11 '12 at 18:04
  • A literal `` inside a ` – Salman A Dec 11 '12 at 18:20
  • adding elements to the `` portion of the DOM will have no effect after the page is rendered. Therefore, even though you are appending the `script` tag, nothing will happen. You'll want to use a more dynamic approach. – Jason Dec 11 '12 at 18:26
  • Possible duplicate of [How to add DOM element script to head section?](http://stackoverflow.com/questions/18784920/how-to-add-dom-element-script-to-head-section) – T.Todua Feb 14 '17 at 12:12

2 Answers2

4

You can use jquery getScript function:

http://api.jquery.com/jQuery.getScript/

so the correct code looks like the below:

 $.getScript('files/js/niceEdit.js');
AlecTMH
  • 2,615
  • 23
  • 26
2

One of the problems in your script is that the </script> inside the string literal actually breaks the outer <script> tag. You might notice these characters in your page which seem to come out of nowhere:

');};

Secondly, while it is still possible to inject a <script> tag in the head, there is no direct/easy/cross-browsr way of knowing when the script has finished loading. And you cannot use a script before it is loaded completely.

Best solution is to use jQuery.getScript() which provides a callback. Use the callback to call nicEditors.allTextAreas() function:

$(document).ready(function () {
    if ($("textarea").length > 0) {
        $.getScript("files/js/nicEdit.js", function () {
            // no need for onDomLoaded -- DOM is loaded at this point!
            nicEditors.allTextAreas();
        });
    }
});
Salman A
  • 262,204
  • 82
  • 430
  • 521