简体   繁体   中英

Best practice to use/add JavaScript and CSS in TYPO3-Extension

Best Practise?

Given: I build a extension for a TYPO3-website which needs a javaScript-Framework-Plugin (jQuery-datepicker), some JavaScript-Code (dropdown-UI) for the template and on page some sepcial JavaScript-Parameter (JSON with DATAS for DataTables).

Question:

How should I add the javascript? BestPractice for the javaScript-parameter, for the special Javascript-code and for JavaScript-Framework-Plugin?

  1. via Fluid HeaderAssests (JSON(will it work?), Special Code,Framework)
  2. via TypoScript with convention, that the typoscript 'page.includeJS' refer to 'page = PAGE" in the typoscript of the sitepackage-Extension (Special Code, Framework)
  3. via Controller/Pagarenderer in my plugin ( Special Code, Framework)
  4. via typoScript in ext_typoscript_setup.typoscript and ext_typoscript_constants.typoscript (JSON, Special Code, Framework)
  5. via HTML-script-tag in the Fluid-Template (JSON, Special Code,Framework)
  6. via Data-attribute in some special Tags? (JSON, Special Code)
  7. ... or are there other ways??

In TYPO3 exists an Icon-API. Exists something similiar for JavaScript oder Stylesheets?

Everything that is basically a library like jquery or your custom JavaScript I would recommend page.includeJS

# third party
page.includeJS.jquery = EXT:ext/Resources/Public/JavaScript/Contrib/jquery.js
# everything that consumes data add to footer
page.includeJSFooter.dropui = EXT:ext/Resources/Public/JavaScript/dropui.js

Data which can be consumed by the libraries like a list or some sort of data which can be structure as json object, I do:

in extbase controller:

$values = ['name' => 'Thomas', 'age' => '38'];
$this->view->assign("my_data_json", json_encode($values));

in template:

<script type='text/javascript'>
    /*  <f:format.cdata> */
    var my_data = <f:format.raw>{my_data_json}</f:format.raw>;
    /*  </f:format.cdata> */
</script>

Now your library can pickup the my_data variable and do stuff. A script, that consumes my_data must be includes after with page.includeJSFooter

For own use you are free, which way to go. If you publish your extension for other use cases JS and CSS should be configurable to load or not to load. I prefer the TypoScript way like EXT:fluid_styled_content, which offers separate TypoScript setup file, to include styles optional. In TypoScript setup you can use all given possibilities to load CSS and JS:

# CSS
plugin.tx_myextension._CSS_DEFAULT_STYLE { ... }

# JS
page.includeJS.myfile = EXT:myextension/Resources/Public/JavaScript/myfile.js
page.includeJS.myfile.type = text/javascript

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