orestbida / cookieconsent

:cookie: Simple cross-browser cookie-consent plugin written in vanilla js
https://playground.cookieconsent.orestbida.com/
MIT License
3.85k stars 405 forks source link

How to Load Scripts with HTML Attributes #10

Closed be-studio closed 3 years ago

be-studio commented 3 years ago

I am using the loadScript function to run a script whose script start tag has attributes.

For example, if I run a script that would normally be run like so:

<script src="https://example.com/example.js"></script>

Using loadScript I would use:

cc.loadScript("https://example.com/example.js");

But, how would I use loadScript with something like this:

<script src="https://example.com/example.js" id="someId" class="someClass" data-code="someData"></script>

Is it possible to pass those script start tag attributes to loadScript?

orestbida commented 3 years ago

Hi, you can easily achieve this by passing an array of objects as a third parameter to the loadScript(<path>, <callback function>, <optional params>) like so:

cc.loadScript('https://example.com/example.js', function(){     
   // ... do something if needed
}, [
   {name: 'id', value: 'myid'},
   {name: 'class', value: 'myclass'},
   {name: 'data-code', value: 'somedata'},
]);

I'll update the readme.md with this "hidden feature"

be-studio commented 3 years ago

Thank you @orestbida for the very prompt response. It works! But one other quick question. If I have a script start tag like so:

<script src="https://example.com/example.js" async id="someId"></script>

How would I pass async to loadScript? Would it be:

...
{ name: "async", value: true }
...

...perhaps?

orestbida commented 3 years ago

I'm not sure value: true would work, if it doesn't work then try with a blank value like so:

{name: 'async', value: ''}
be-studio commented 3 years ago

Well, I've tried my suggestion. I've also tried a value of a blank string and a value of null and the script loads fine in all cases, but I can't be sure that they load say async as in my example. And I don't have any other scripts where I have attributes without a value that I can try.

Thank you @orestbida , nevertheless, for this library...it works very well and serves all my purposes :-) Good job!

orestbida commented 3 years ago

From my testing i can tell you this:

if you've loaded the cookieconsent.js file with the defer attribute:

<script src="<path_to_cookieconsent.js>" defer></script>

then adding async or defer to the dynamically loaded scripts with the .loadScript() method will (most likely) not make any difference at all (since the page has alredy been fully loaded).

There might however be some edge cases where the website is exceptionally slow or the cookieconsent.js is loaded without defer or async. In these cases it might be useful to also add async/defer.

Also, thank you ;), closing this issue!