function advagg_mod_xpath_script_wrapper in Advanced CSS/JS Aggregation 7.2
Use DOMDocument's loadHTML along with DOMXPath's query to find script tags.
Once found, it will also wrap them in a javascript loader function.
Parameters
string $html: HTML fragments.
Return value
string The HTML fragment with less markup errors and script tags wrapped.
1 call to advagg_mod_xpath_script_wrapper()
- advagg_mod_js_inline_processor in advagg_mod/
advagg_mod.module - Given html, do some processing on the script tags included inside it.
File
- advagg_mod/
advagg_mod.module, line 2788 - Advanced aggregation modifier module.
Code
function advagg_mod_xpath_script_wrapper($html) {
// Do not throw errors when parsing the html.
libxml_use_internal_errors(TRUE);
$dom = new DOMDocument();
// Load html with full tags all around.
$dom
->loadHTML('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body>' . $html . '</body></html>');
$xpath = new DOMXPath($dom);
// Get all script tags that
// are not inside of a textarea
// do not contain a src attribute
// and the type is empty or has the type of javascript.
$nodes = $xpath
->query("//script[not(@src)][not(ancestor::textarea)][contains(translate(@type, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'javascript') or not(@type)]");
foreach ($nodes as $node) {
$matches[2] = $node->nodeValue;
// $matches[0] = $dom->saveHTML($node);
$matches[0] = $node->nodeValue;
$new_html = advagg_mod_wrap_inline_js($matches);
$advagg = $dom
->createElement('script');
$advagg
->appendchild($dom
->createTextNode($new_html));
$node->parentNode
->replaceChild($advagg, $node);
}
// Render to HTML.
$output = $dom
->saveHTML();
// Remove the tags we added.
$output = str_replace(array(
'<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body>',
'</body></html>',
), array(
'',
'',
), $output);
// Clear any errors.
libxml_clear_errors();
return $output;
}