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 Arshad
274k85 gold badges450 silver badges540 bronze badges
asked Dec 11, 2012 at 17:52
4
  • I don't see how your demo could work. What is nicEditors? Commented Dec 11, 2012 at 18:04
  • A literal </script> inside a <script> tag will break the script tag! Commented Dec 11, 2012 at 18:20
  • adding elements to the <head> 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. Commented Dec 11, 2012 at 18:26
  • Possible duplicate of How to add DOM element script to head section? Commented Feb 14, 2017 at 12:12

2 Answers 2

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');
answered Dec 11, 2012 at 18:14
Sign up to request clarification or add additional context in comments.

Comments

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();
 });
 }
});
answered Dec 11, 2012 at 18:23

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.