4

I am working with a system where I cannot directly edit the HTML on each page. I want to add the top of the body of a particular page but the box where I enter the HTML automatically places the script just above

I tried this:

<script>
$('body').prepend('<script src="myscript.js"></script>');
</script>

Any help would be greatly appreciated, Thank you!

17
  • Why not simply do: $.getScript('myscript.js');? Docs: api.jquery.com/jQuery.getScript Commented Mar 25, 2014 at 16:58
  • 1
    Why do you think you need to add the script to just above the body tag? Commented Mar 25, 2014 at 17:00
  • 1
    @Jenny: Does it actually matter where the script is placed? Or are they just telling you that? Have you tried putting the script elsewhere (by just doing <script src="myscript.js"></script> in the HTML) to see if it works? Also, where are you running your script? Commented Mar 25, 2014 at 17:06
  • 2
    @Jenny - why do they require it place there? To be technical about it, if you are appending the script tag to the page with JavaScript, then the entire reason of placing the script tag before the body tag has already been defeated. Commented Mar 25, 2014 at 17:11
  • 1
    @Jenny: If their script only works at the top of the body, then that means they are doing something wrong. Commented Mar 25, 2014 at 17:39

1 Answer 1

0

I don't understand why you are doing this, but it is possible... :)

If you must insert javascript code at the begining of the tag body, you can load your javascript file like a "jsonp ajax call" and inside it call to 'prepend' jquery function.

Example:

<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <h1>Test</h1>
    <p>Test</p>
    <script type="text/javascript" src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
    <script type="text/javascript">
      $( document ).ready( function() {
        $.ajax({
          dataType: "jsonp",
          url: "myscript.js"
        })
        .done( function( d, response ) {
          console.log( "JS LOADED" );
        });
      });
    </script>
  </body>
</html>

And in your "myscript.js" file something like:

$( "body" ).prepend( "<script>" +
                     "var a = 1;" +
                     "console.log( a );" + 
                     "/* AND ALL THE JS CODE TO INSERT " +
                     "AT THE BEGINING OF TAG BODY */</script>" );

Don't forget with the semicolon (;) at the end of every js line.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.