Reputation: 10790
We allow users to place a
<script language="javascript" src="oursite/script.php"></script>
tag on their page which should then embed some content from our site into their site. Currently script.php contains document.write("some content loaded from the database"), however there are some limitations.
Is there anyway I can have the same thing achieved using jQuery ? How do i tell jQuery to put a certain piece of HTML code EXACTLY where the script tag is ? document.write() can do this, but i'm not sure how to do this using jquery. (we are already providing the jquery js code to the client through script.php.
Upvotes: 0
Views: 1560
Reputation: 31621
You don't necessarily need to use jQuery, but you can.
The basic problem here is finding the script node as the page is loading.
You can give it an id
and hope there are no duplicate ids on the other user's page.
But if you know the script will be evaluated as the page is loading, you can also do this:
(function(){ // this is just so you don't run into name collisions with the user's page
// Get all script elements
var scripts = document.getElementsByTagName('script');
// we know the last script element will be *this* one
var script = scripts[scripts.length-1];
var newp = document.createElement('p');
newp.textContent = 'inserted paragraph';
// now insert our new nodes after the current script
script.parentNode.insertBefore(newp, script.nextSibling);
})();
You can of course use jQuery as well with var $script = $('script:last');
, but if you don't need it for anything else you can save some loading time by not using it.
Upvotes: 0
Reputation: 91497
You don't need jQuery to do a document.write()
. As long as it is executed inline (ie, not in an event handler such as $(document).ready()
), it will work. Just make sure you escape the end script tag (like this: <\/script>
), so that the HTML parser doesn't mistake it for an actual end script tag:
<script type="text/javascript">
document.write("<script language=\"javascript\" " +
"src=\"oursite/script.php\"><\/script>");
</script>
Alternatively, you could add the script using DOM manipulations. If you want to add the script after the page has loaded, this is your only option. To position it after the script tag that is calling it, give your script tag an id and use $("#myScript").after("<script>")
:
<script type="text/javascript" id="myScript">
$(function () {
$("#myScript").after("<script>").attr({
language: "javascript",
src: "oursite/script.php"
});
});
</script>
Upvotes: 2