Ask your WordPress questions! Pay money and get answers fast! (more info)

wp_enqueue_script - using dynamic code from variable?

  • SOLVED

I want to optimize my plugin mapsmarker.com by placing all js into the footer. Problem is, that the javascript for each maps gets created on the fly by extracting the shortcode [mapsmarker...] and placing the js inline into the content. This doesnt allow my to put leaflet.js into the footer as it has to be loaded before the dynamic js.

Is there a way to enqueue this dynamic script into the footer? I tried the following by assigning the js code into an extra variable and placing this via wp_enqueue_scripts into the footer:

$lmm1_out = '<script type="text/javascript">'.PHP_EOL;
$lmm1_out .= '/* <![CDATA[ */'.PHP_EOL;
$lmm1_out .= 'alert("test");'.PHP_EOL;
$lmm1_out .= '/* ]]> */'.PHP_EOL;
$lmm1_out .= '</script>'.PHP_EOL;
wp_enqueue_script( 'leafletmapsmarker-js-out', $lmm1_out, array(), $plugin_version, true);


Unfortunately, wp_enqueue_script only allows URL as source parameter and wont accept $lmm1_out, which results into the following output in the code:

<script type='text/javascript' src='http://www.mapsmarker.comscripttype=text/javascript/*!CDATA*/alert(test);/**//script?ver=2.7.1'></script>

Does anyone know a way how to solve this?

Answers (4)

2012-08-04

Hai Bui answers:

I think you can use wp_localize_script, check http://ottopress.com/2010/passing-parameters-from-php-to-javascripts-in-plugins/


Robert Harm comments:

unfortunately, wp_localize_script is not an option here...

2012-08-04

Dbranes answers:

Maybe you could just write your own dynamic javascript file with php:

myscript.php:

<?php
header("content-type: application/x-javascript");
?>
...your javascript code...


and then you could use wp_enqueue_script to call myscript.php.

If you need to access wordpress functions in myscript.php you could use something like:

<?php
header("content-type: application/x-javascript");

// Include WordPress
define('WP_USE_THEMES', false);
require('/server/path/to/your/wp-blog-header.php');
?>
...your javascript code...




Dbranes comments:


... so this could be one way to pass parameters to the dynamic-javascript file:

myscript.php&param1=value1&param2=value2

through wp_enqueue_script


Robert Harm comments:

unfortunately also not an option - the shortcode for creating mals is placed within posts/pages content and the js is created dynamically. So I cant add a file in advance as you suggest...

2012-08-04

Dylan Kuhn answers:

I think you'd have to print it in the footer yourself instead of enqueueing it. A poor practice, but you're desperate right?


$lmm1_out = '<script type="text/javascript">'.PHP_EOL;
$lmm1_out .= '/* <![CDATA[ */'.PHP_EOL;
$lmm1_out .= 'alert("test");'.PHP_EOL;
$lmm1_out .= '/* ]]> */'.PHP_EOL;
$lmm1_out .= '</script>'.PHP_EOL;

function prefix_print_script() {
echo $lmm1_out;
}
add_action( 'wp_footer', 'prefix_print_script' );


Robert Harm comments:

Not desparate, just eager to make my plugin better ;-)
Your solution could work, only thing I have to check is if the scripts wont get displayed before javascripts added to footer via enqueue_script()


Dylan Kuhn comments:

Hai Bui's answer is what would make it better. What's keeping you from using wp_localize_script()? It will work when a shortcode is processed, you just have to make sure the $in_footer parameter to wp_enqueue_script() is true.


Robert Harm comments:

mhhh - the problem is, that wp_enqueue_script for leaflet.js gets executed before the code for the shorttag & wp_localize_script has to be executed after the according script (leaflet.js). I am not sure, it this is possible, will try...


Dylan Kuhn comments:

That doesn't make the dependencies entirely clear to me, but if your script just needs to run after leaflet.js, list that as a dependency. So if wp_enqueue_script() has already been called with a handle of 'leaflet', and your script file is leafletmapsmarker.js, you'd do something like



wp_enqueue_script( 'leafletmapsmarker', '/path/to/leafletmapsmarker.js', array( 'leaflet' ), $plugin_version, true );

$leaflet_marker_variables = array( 'var1' => $var1, 'var2' => $var2 );

wp_localize_script( 'leafletmapsmarker', 'LeafletMapsMarkerConfig', $leaflet_marker_variables );



Your static script will have the variables it needs in LeafletMapsMarkerConfig, and be loaded after leaflet.js.


Robert Harm comments:

thanks, but I fear I didnt express my self clear enough: I use the shortcode eg [mapsmarker marker="1"] in posts/page content to dynamically create code like this:

<div id="lmm_8fe4d160" style="width:900px;">
<div id="lmm_panel_8fe4d160" class="lmm-panel" style="background: #efefef;">
<div id="lmm_panel_api_8fe4d160" class="lmm-panel-api"><a href="http://maps.google.com/maps?daddr=48.216038,16.378984&t=m&layer=1&doflg=ptk&hl=en&om=0" target="_blank" title="Get directions"><img src="http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/icon-car.png" width="14" height="14" class="lmm-panel-api-images" /></a><a href="http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/leaflet-kml.php?marker=242&name=show" style="text-decoration:none;" title="Export as KML for Google Earth/Google Maps"><img src="http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/icon-kml.png" width="14" height="14" alt="KML-Logo" class="lmm-panel-api-images" /></a><a href="http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/leaflet-fullscreen.php?marker=242" style="text-decoration:none;" title="Open standalone map in fullscreen mode" target="_blank"><img src="http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/icon-fullscreen.png" width="14" height="14" alt="Fullscreen-Logo" class="lmm-panel-api-images" /></a><a href="https://chart.googleapis.com/chart?chs=150x150&cht=qr&chl=http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/leaflet-fullscreen.php?marker=242" target="_blank" title="Create QR code image for standalone map in fullscreen mode"><img src="http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/icon-qr-code.png" width="14" height="14" alt="QR-code-logo" class="lmm-panel-api-images" /></a><a href="http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/leaflet-geojson.php?marker=242&callback=jsonp&full=yes" style="text-decoration:none;" title="Export as GeoJSON" target="_blank"><img src="http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/icon-json.png" width="14" height="14" alt="GeoJSON-Logo" class="lmm-panel-api-images" /></a><a href="http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/leaflet-georss.php?marker=242" style="text-decoration:none;" title="Export as GeoRSS" target="_blank"><img src="http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/icon-georss.png" width="14" height="14" alt="GeoRSS-Logo" class="lmm-panel-api-images" /></a><a href="http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/leaflet-wikitude.php?marker=242" style="text-decoration:none;" title="Export as ARML for Wikitude Augmented-Reality browser" target="_blank"><img src="http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/icon-wikitude.png" width="14" height="14" alt="Wikitude-Logo" class="lmm-panel-api-images" /></a></div><div id="lmm_panel_text_8fe4d160" class="lmm-panel-text" style="padding-left:5px;font-weight:bold;">'</div></div>
<div id="lmm_map_8fe4d160" data-marker="242" style="height:480px; overflow:hidden;padding:0;"></div>
<div id="lmm_geo_tags_8fe4d160" class="lmm-geo-tags geo">
<span class="paneltext">\'</span>
<span class="latitude">48.216038</span>, <span class="longitude">16.378984</span>
<span class="popuptext">\"</span>
</div>
<script type="text/javascript">
/* <![CDATA[ */
/* Maps created with MapsMarker.com (WordPress Plugin powered by Leaflet from Cloudmade) - version 2.7.1 */
var layers = {};
var markers = {};
var lmm_map_8fe4d160 = {};
(function($) {
lmm_map_8fe4d160 = new L.Map("lmm_map_8fe4d160", { dragging: true, touchZoom: true, scrollWheelZoom: true, doubleClickZoom: true, zoomControl: true, trackResize: true, closePopupOnClick: true, crs: L.CRS.EPSG3857 });
lmm_map_8fe4d160.attributionControl.setPrefix("<a href=\"http://mapsmarker.com/go\" target=\"_blank\" title=\"powered by 'Leaflet Maps Marker'-Plugin for WordPress\">MapsMarker.com</a> (<a href=\"http://leaflet.cloudmade.com\" target=\"_blank\" title=\"'Leaflet Maps Marker' uses the JavaScript library 'Leaflet' for interactive maps by CloudMade\">Leaflet</a>, <a href=\"http://mapicons.nicolasmollet.com\" target=\"_blank\" title=\"'Leaflet Maps Marker' uses icons from the 'Maps Icons Collection'\">Icons</a>)");
var osm_mapnik = new L.TileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {maxZoom: 18, minZoom: 1, errorTileUrl: "http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/error-tile-image.png", attribution: "Map: &copy; 2012 <a href=\"http://www.openstreetmap.org\" target=\"_blank\">OpenStreetMap contributors</a>, <a href=\"http://creativecommons.org/licenses/by-sa/2.0/\" target=\"_blank\">CC-BY-SA</a>"});
var mapquest_osm = new L.TileLayer("http://{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png", {maxZoom: 18, minZoom: 1, errorTileUrl: "http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/error-tile-image.png", attribution: "Map: Tiles Courtesy of <a href=\"http://www.mapquest.com/\" target=\"_blank\">MapQuest</a> <img src=\"http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/logo-mapquest.png\" style=\"\" />", subdomains: ["otile1","otile2","otile3","otile4"]});
var mapquest_aerial = new L.TileLayer("http://{s}.mqcdn.com/naip/{z}/{x}/{y}.png", {maxZoom: 18, minZoom: 1, errorTileUrl: "http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/error-tile-image.png", attribution: "Map: <a href=\"http://www.mapquest.com/\" target=\"_blank\">MapQuest</a> <img src=\"http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/logo-mapquest.png\" />, Portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency", subdomains: ["oatile1","oatile2","oatile3","oatile4"]});
var googleLayer_roadmap = new L.Google("ROADMAP");
var googleLayer_satellite = new L.Google("SATELLITE");
var googleLayer_hybrid = new L.Google("HYBRID");
var googleLayer_terrain = new L.Google("TERRAIN");
var bingaerial = new L.BingLayer("Agj2Jczv837wHWeeM10JbkthyPBN2-0w4IvzNuXS9Wqrixod0hMXSzFt5mpzLTQR", {type: "Aerial", maxZoom: 21, minZoom: 1, errorTileUrl: "http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/error-tile-image.png"});
var bingaerialwithlabels = new L.BingLayer("Agj2Jczv837wHWeeM10JbkthyPBN2-0w4IvzNuXS9Wqrixod0hMXSzFt5mpzLTQR", {type: "AerialWithLabels", maxZoom: 21, minZoom: 1, errorTileUrl: "http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/error-tile-image.png"});
var bingroad = new L.BingLayer("Agj2Jczv837wHWeeM10JbkthyPBN2-0w4IvzNuXS9Wqrixod0hMXSzFt5mpzLTQR", {type: "Road", maxZoom: 21, minZoom: 1, errorTileUrl: "http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/error-tile-image.png"});
var ogdwien_basemap = new L.TileLayer("http://{s}.wien.gv.at/wmts/fmzk/pastell/google3857/{z}/{y}/{x}.jpeg", {maxZoom: 19, minZoom: 11, errorTileUrl: "http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/error-tile-image.png", attribution: "Map: City of Vienna (<a href=\"http://data.wien.gv.at\" target=\"_blank\" style=\"\">data.wien.gv.at</a>)", subdomains: ["maps","maps1", "maps2", "maps3"]});
var ogdwien_satellite = new L.TileLayer("http://{s}.wien.gv.at/wmts/lb/farbe/google3857/{z}/{y}/{x}.jpeg", {maxZoom: 19, minZoom: 11, errorTileUrl: "http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/error-tile-image.png", attribution: "Map: City of Vienna (<a href=\"http://data.wien.gv.at\" target=\"_blank\">data.wien.gv.at</a>)", subdomains: ["maps","maps1", "maps2", "maps3"]});
var cloudmade = new L.TileLayer("http:[email protected]/256/{z}/{x}/{y}.png", {maxZoom: 19, minZoom: 1, errorTileUrl: "http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/error-tile-image.png", attribution: "Map: &copy; 2012 <a href=\"http://www.openstreetmap.org\" target=\"_blank\" style=\"\">OpenStreetMap contributors</a>, <a href=\"http://creativecommons.org/licenses/by-sa/2.0/\" target=\"_blank\">CC-BY-SA</a>, Imagery &copy; <a href=\"http://cloudmade.com\" target=\"_blank\">CloudMade</a>", subdomains: ["a","b","c"]});
var cloudmade2 = new L.TileLayer("http:[email protected]/256/{z}/{x}/{y}.png", {maxZoom: 19, minZoom: 1, errorTileUrl: "http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/error-tile-image.png", attribution: "Map: &copy; 2012 <a href=\"http://www.openstreetmap.org\" target=\"_blank\" style=\"\">OpenStreetMap contributors</a>, <a href=\"http://creativecommons.org/licenses/by-sa/2.0/\" target=\"_blank\">CC-BY-SA</a>, Imagery &copy; <a href=\"http://cloudmade.com\" target=\"_blank\">CloudMade</a>", subdomains: ["a","b","c"]});
var cloudmade3 = new L.TileLayer("http:[email protected]/256/{z}/{x}/{y}.png", {maxZoom: 19, minZoom: 1, errorTileUrl: "http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/error-tile-image.png", attribution: "Map: &copy; 2012 <a href=\"http://www.openstreetmap.org\" target=\"_blank\" style=\"\">OpenStreetMap contributors</a>, <a href=\"http://creativecommons.org/licenses/by-sa/2.0/\" target=\"_blank\">CC-BY-SA</a>, Imagery &copy; <a href=\"http://cloudmade.com\" target=\"_blank\">CloudMade</a>", subdomains: ["a","b","c"]});
var mapbox = new L.TileLayer("http://{s}.tiles.mapbox.com/v3/mapbox.blue-marble-topo-jul/{z}/{x}/{y}.png", {minZoom: 0, maxZoom: 8, errorTileUrl: "http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/error-tile-image.png", attribution: "MapBox/NASA, <a href=\"http://www.mapbox.com\" target=\"_blank\">http://www.mapbox.com</a>", subdomains: ["a","b","c","d"]});
var mapbox2 = new L.TileLayer("http://{s}.tiles.mapbox.com/v3/mapbox.geography-class/{z}/{x}/{y}.png", {minZoom: 0, maxZoom: 8, errorTileUrl: "http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/error-tile-image.png", attribution: "MapBox, <a href=\"http://www.mapbox.com\" target=\"_blank\">http://www.mapbox.com</a>", subdomains: ["a","b","c","d"]});
var mapbox3 = new L.TileLayer("http://{s}.tiles.mapbox.com/v3/mapbox.mapbox-streets/{z}/{x}/{y}.png", {minZoom: 0, maxZoom: 17, errorTileUrl: "http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/error-tile-image.png", attribution: "MapBox, <a href=\"http://www.mapbox.com\" target=\"_blank\">http://www.mapbox.com</a>", subdomains: ["a","b","c","d"]});
var custom_basemap = new L.TileLayer("http://{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png", {maxZoom: 18, minZoom: 1, errorTileUrl: "http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/error-tile-image.png", attribution: "Map: Copyright 2012 <a href=\"http://xy.com\">Provider X</a>", subdomains: ["otile1", "otile2", "otile3", "otile4"]});
var custom_basemap2 = new L.TileLayer("http://{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png", {maxZoom: 18, minZoom: 1, errorTileUrl: "http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/error-tile-image.png", attribution: "Map: Copyright 2012 <a href=\"http://xy.com\">Provider Y</a>", subdomains: ["otile1", "otile2", "otile3", "otile4"]});
var custom_basemap3 = new L.TileLayer("http://{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png", {maxZoom: 18, minZoom: 1, errorTileUrl: "http://current.mapsmarker.com/wp-content/plugins/leaflet-maps-marker/img/error-tile-image.png", attribution: "Map: Copyright 2012 <a href=\"http://xy.com\">Provider Z</a>", subdomains: ["otile1", "otile2", "otile3", "otile4"]});
var layersControl = new L.Control.Layers(
{'OSM Mapnik': osm_mapnik,'Mapquest OSM': mapquest_osm,'Mapquest (Aerial)': mapquest_aerial,'Google Maps (Roadmap)': googleLayer_roadmap,'Google Maps (Satellite)': googleLayer_satellite,'Google Maps (Hybrid)': googleLayer_hybrid,'Google Maps (Terrain)': googleLayer_terrain,'Bing Maps (Aerial)': bingaerial,'Bing Maps (AerialLabels)': bingaerialwithlabels,'Bing Maps (Road)': bingroad,'OGD Vienna basemap': ogdwien_basemap,'OGD Vienna satellite': ogdwien_satellite},
{},
{ collapsed: !L.Browser.touch } );
lmm_map_8fe4d160.setView(new L.LatLng(48.216038, 16.378984), 11);
lmm_map_8fe4d160.addLayer(ogdwien_basemap).addControl(layersControl);
var marker = new L.Marker(new L.LatLng(48.216038, 16.378984));
lmm_map_8fe4d160.addLayer(marker);
marker.bindPopup("\"<div style='border-top:1px solid #f0f0e7;padding-top:5px;margin-top:5px;'><a href=http://maps.google.com/maps?daddr=48.216038,16.378984&t=m&layer=1&doflg=ptk&hl=en&om=0 target='_blank' title='Get directions'>Directions</a></div>");
})(jQuery);
/* ]] > */
</script>
</div>


the problem is, that if I have 3 shortcodes on a page, 3 maps with 3 inline javascript-code get created. I need to move these to the footer. So there is no static js like leafletmapsmarker.js you pointed out in your example...


Dylan Kuhn comments:

I can see some problems with that approach, but I don't see what simply moving those inline scripts to footer will improve.

My suspicion is that even if you could use wp_enqueue_script() to queue script code instead of a file, your problems would not be solved. I'd suggest going for a single static script that can create multiple maps from arrays of div IDs and corresponding marker IDs created when the shortcodes are processed, but not enqueued until wp_footer runs.


Robert Harm comments:

what I actually try to improve is the load time - especially by moving google maps api-js & leaflet.js to footer (which are about 87kb) and need to be loaded before the inline js.

well anyway thanks for your suggestion - this might be a bit tricky but at least a possible approach for further versions...

2012-08-04

Martin Pham answers:

try this

function custom_lmm1_script() {
$output = '/* <![CDATA[ */
alert("test")
/* ]]> */
';
$output = str_replace( array( "\n", "\t", "\r" ), '', $output );
echo '<script type=\'text/javascript\'>' . $output . '</script>';
}

You can put on Header or footer

Header:

add_action( 'wp_head', 'custom_lmm1_script', 20 );


Or Footer

add_action( 'wp_footer', 'custom_lmm1_script' );


Robert Harm comments:

will try...