简体   繁体   中英

Joomla! add script in document head from article

We have a couple of pages that require special care, jquery-ui will be called from external scripts which are going to "somehow" be added to the head section of an article.

I've attempted with jumi, however it isn't the best choice(including a js in stead of php would render it in html body), the only way I could add a javascript file was by including a php file which would echo a , but as one would imagine, this isn't elegant nor efficient in terms of performance.

Another attempt was, in stead of echoing a script, I've tried using:

<?php
  $document = &JFactory::getDocument();
  $document->addScript( "path/to/jsfile.js" );
?>

but it didn't work as I've expected, it seems that joomla creates the head section before this php script has the chance of being executed.

I've also gave easy header a go, however, it seems that it will include the files in all articles, which I do not wish since it will have a pretty big impact in terms of bandwidth and possible javascript issues down the road.

I'm farily new to joomla so anything that would provide some flexibility is good as an answer.

If something isn't unclear, please ask, I will try to answer the best I can.

Please note that I'm using joomla 1.7 and php5.

Jumi uses the onAfterRender event (looking at the 2.0.6 plugin) - by this time I think the <head> tag has already been written out, in-fact the whole document is already rendered.

You could try getting the document body and then searching for the closing tag </head> and inserting the script link before it. Something like this:

$myJS    = "<script type='text/javascript' src='http://mysever.com/my.js'>"
$content = JResponse::getBody(); // gets the html in it's ready to send to browser form
$hdPos   = strpos($content, '</head>');
$hdPos  += 7;  //move position to include the <head> tag
$bodyLen = strlen($content);
$content = substr($content, 0, $hdPos) . $myJS . substr($content, $hdPos, $bodyLen);
JResponse::setBody($content);

NB: This is untested and I don't use Jumi these days but it should be close.

You didn't have to go through all this! Go to: extensions -> template manager -> templates tab (its on "styles" by default) -> go to your template and click on "edit HTML". You'll be able to add your code directly in the header, and it will be loaded in all the pages.

A bit more elegant way is to define a function that does what you want in the header - and call it from the body of the specific article you want.

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